[英]Throwing error from subscription/observable - Angular2+
我試圖從觀察到的函數中拋出錯誤,以便可以訪問訂閱的err
部分,但似乎無法理解該部分。
我不確定如何通過地圖方式進行操作,但是這是另一種方式:
import { Observable, of, throwError } from 'rxjs';
ngOnInit() {
this.getObs().subscribe(data => {
console.log(data);
}, err => {
console.log(err);
});
}
getObs() {
const observable = of(6);
const isError = true;
if (isError) {
return throwError("Is an error!");
}
return observable;
}
工作示例: https : //stackblitz.com/edit/angular-mqp4qv?file=src/app/app.component.ts
我將通過幾種方式來處理此問題。 繼承人使用_throw的一種方法
// auth.ts
import { _throw } from 'rxjs/observable/throw';
login( username, password ) {
const body = this.jsonifyData( username, password );
return this.http.post<any>( this.apiBaseUrl + '/auth', body )
.pipe(
map( res => {
if ( 'token' in res ) {
return res.token;
}
// Unsuccessful login returns error
return _throw( res ); // from import {_throw} from 'rxjs/observable/throw';
} )
);
}
另一種是只是在登錄組件中捕獲錯誤
我認為在組件的測試規范中,您需要模擬authService
和login
過程。 該模擬不會進行http調用,只是在密碼不匹配某些預定義值的情況下立即通過throwError(new Error('Either username or password were incorrect'))
引發錯誤。 這是一些有關如何測試component-http服務的示例,雖然有些過時,但從概念上講仍然是實際的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.