2017-05-09 32 views
2

我正在關注此鏈接上的教程here從Angular 2的Observable中捕獲錯誤的正確方法是什麼?

作者在這裏做了些什麼,我不太明白。在catchAuthError方法中,他將服務自己的實例作爲self傳遞,但他不在方法本身中使用該變量。

import {Injectable} from '@angular/core'; 
import {Http, XHRBackend, RequestOptions, Request, RequestOptionsArgs, Response, Headers} from '@angular/http'; 
import {Observable} from 'rxjs/Observable'; 
import 'rxjs/add/operator/map'; 
import 'rxjs/add/operator/catch'; 

@Injectable() 
export class HttpService extends Http { 

    constructor (backend: XHRBackend, options: RequestOptions) { 
    let token = localStorage.getItem('auth_token'); // your custom token getter function here 
    options.headers.set('Authorization', `Bearer ${token}`); 
    super(backend, options); 
    } 

    request(url: string|Request, options?: RequestOptionsArgs): Observable<Response> { 
    let token = localStorage.getItem('auth_token'); 
    if (typeof url === 'string') { // meaning we have to add the token to the options, not in url 
     if (!options) { 
     // let's make option object 
     options = {headers: new Headers()}; 
     } 
     options.headers.set('Authorization', `Bearer ${token}`); 
    } else { 
    // we have to add the token to the url object 
     url.headers.set('Authorization', `Bearer ${token}`); 
    } 
    return super.request(url, options).catch(this.catchAuthError(this)); 
    } 

    private catchAuthError (self: HttpService) { 
    // we have to pass HttpService's own instance here as `self` 
    return (res: Response) => { 
     console.log(res); 
     if (res.status === 401 || res.status === 403) { 
     // if not authenticated 
     console.log(res); 
     } 
     return Observable.throw(res); 
    }; 
    } 
} 

在評論,它說:

we have to pass HttpService's own instance here as self

爲什麼這是必要的,我應該怎麼趕上在這種情況下的錯誤?什麼是正確的方法?

回答

2

return super.request(url, options).catch(this.catchAuthError(this)); 

return super.request(url, options).catch(this.catchAuthError.bind(this)); 

return super.request(url, options).catch((err)=>this.catchAuthError(err)); 

實際上是相同的東西,你是在最後2和第一個1,你正在創建一個閉合給出指向你的組件的this。但是你是對的,在這種情況下它是不必要的,因爲它沒有被使用。

resreturn (res: Response) => {等於我的第三個例子中的錯誤對象。


筆者可曾想過好歹使用超類中,但在我看來, this例如,這僅僅是一個令人困惑的例子,可以簡化爲這樣:

return super.request(url, options).catch((error)=>this.catchAuthError(error)); 


private catchAuthError (error) { 
     if (error.status === 401 || error.status === 403) { 
     // if not authenticated 
     console.log(error); 
     } 
     return Observable.throw(error); 
    }; 
    } 
+0

謝謝你先生! – Alex

+0

@亞歷山大最受歡迎的先生 – echonax

+0

我得到了錯誤:EXCEPTION:Observable_1.Observable.throw不是一個函數。我必須這樣做:導入'rxjs/add/observable/throw';? – Alex

相關問題