2017-05-09 20 views
10

Tôi đang cố thêm bộ nạp tải vào mọi yêu cầu kết thúc bằng Angular 2, vì vậy tôi đã mở rộng dịch vụ Http gọi nó là HttpService. Sau mỗi yêu cầu, tôi muốn gọi hàm finally() sau khi bắt lỗi để tôi có thể dừng trình quay tải.Tại sao cuối cùng() không hoạt động sau khi bắt trên một Observable trong Angular 2?

Nhưng nguyên cảo nói:

[ts] tài sản 'cuối cùng' không tồn tại trên loại 'Quan sát'.

import { AuthService } from './../../auth/auth.service'; 
import { Injectable } from '@angular/core'; 
import { Http, XHRBackend, RequestOptions, RequestOptionsArgs, Request, Response, Headers } from '@angular/http'; 

import { Observable } from 'rxjs/Observable'; 
import 'rxjs/add/operator/catch'; 
import 'rxjs/add/observable/throw'; 

@Injectable() 
export class HttpService extends Http { 

    constructor(
     backend: XHRBackend, 
     options: RequestOptions, 
     private authservice: AuthService 
    ) { 
     super(backend, options); 
     this.updateHeaders(options.headers); 
    } 

    request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> { 
     return super.request(url, options) 
      .catch((response: Response) => this.authError(response)) 
      .finally(() => { 
       // ... 
       /* Do something here when request is done. For example 
       finish a spinning loader. */ 
      }); 
    } 

    private authError(response: Response) { 
     if (response.status === 401 || response.status === 403) { 
      this.authservice.logout(); 
     } 
     return Observable.throw(response); 
    } 

    private updateHeaders(headers: Headers) { 
     headers.set('Content-Type', 'application/json'); 
     if (this.authservice.isloggedIn()) { 
      headers.set('Authorization', `Bearer ${this.authservice.getToken()}`); 
     }   
    } 
} 

Làm thế nào tôi có thể chạy một số mã sau mỗi lần yêu cầu http như thế này? Cách tốt nhất để làm điều đó là gì?

+0

Bạn cần phải nhập khẩu 'finally'. Nên có đủ câu hỏi với câu trả lời giải thích điều đó. –

Trả lời

25

Bạn quên import nó:

import 'rxjs/add/operator/finally'; 
+0

cảm ơn bạn. Tôi đã nhận được lỗi "cuối cùng không phải là một chức năng" và việc thêm nhập này đã khắc phục sự cố của tôi. –

+0

Đã làm việc cho tôi! – Sami

Các vấn đề liên quan