2016-04-28 263 views
1

我遇到了以正確方式訂閱我的http攔截器的問題。我有以下幾點:攔截錯誤並訂閱

post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response>{ 
    return super.post(url,body, {headers: customHeaders}).catch(err =>{ 
      console.log('Error caught in POST at '+url); 
      return Observable.of(err); 
     }); 
    } 

這是好的 - 它記錄每次發佈時發生錯誤。但是,如果我試圖抓住錯誤在其他組件是這樣的:

this.http.post('someurl','somestring') 
    .subscribe(
     success=>{ 
      console.log('success: ',success); 
     }, 
     error=>{ 
      console.log('error: ',error); 
     } 
    ) 

所以現在,當在POST的錯誤我的控制檯日誌打印:

Error caught in POST at someurl 
success: //errorobject here// 

不過,我期待這樣的:

Error caught in POST at someurl 
error: //errorobject here// 

我在做什麼錯?

回答

1

我覺得應該是throw err而不是Observable.of(err)

post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response>{ 
    return super.post(url,body, {headers: customHeaders}).catch(err =>{ 
      console.log('Error caught in POST at '+url); 
      throw err; 
     }); 
    } 
1

我會用Observable.throw,而不是Observable.of

post(url: string, body: any, options?: RequestOptionsArgs): Observable<Response>{ 
    return super.post(url,body, {headers: customHeaders}).catch(err =>{ 
     console.log('Error caught in POST at '+url); 
     return Observable.throw(err); // <-------------- 
    }); 
} 

Observable.of返回一個「成功」可觀察則其將被成功處理在subscribe內回調。

+0

蒂埃裏,我爲你去了一個http://stackoverflow.com/questions/37049848/http-stream-send-twice-instead-of-once :) – uksz