Bhu*_*kar 45 javascript typescript angular2-observables angular
我正在开发angular2 app,我正在通过HTTp进行休息,如下所示:
login(email, password) {
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let options = new RequestOptions({ headers: headers });
let body = `identity=${email}&password=${password}`;
return this.http.post(`${this._configService.getBaseUrl()}/login`, body, options)
.map((res: any) => {
let response: any = JSON.parse(res._body);
if (response.success == 0) {
Observable.throw(response); // not working
} else if (response.success == 1) {
console.log('success');
localStorage.setItem('auth_token', 'authenticated');
this.loggedIn = true;
return response;
}
});
}
Run Code Online (Sandbox Code Playgroud)
基本上我希望我的组件在我的订阅调用中获得响应和错误.
即
this._authenticateService.login(this.loginObj['identity'],this.loginObj['password']).subscribe(
(success)=>{
this.credentialsError=null;
this.loginObj={};
this._router.navigate(['dashboard']);
},
(error)=>{
console.log(error);
this.credentialsError=error;
}
);
Run Code Online (Sandbox Code Playgroud)
但我的api总是返回成功,因为它以这种方式定义.
所以我想知道如何抛出错误消息response.success == 0
,以便在我的订阅回调的错误参数内访问它.
Cap*_*apK 66
rxjs 6
import { throwError } from 'rxjs';
if (response.success == 0) {
return throwError(response);
}
Run Code Online (Sandbox Code Playgroud)
rxjs 5
import { ErrorObservable } from 'rxjs/observable/ErrorObservable';
if (response.success == 0) {
return new ErrorObservable(response);
}
Run Code Online (Sandbox Code Playgroud)
你的回报ErrorObservable
取决于你
Jor*_*ngh 63
if (response.success == 0) {
throw Observable.throw(response);
}
Run Code Online (Sandbox Code Playgroud)
小智 12
RXJS 7
throwError(() => new Error(response))
Run Code Online (Sandbox Code Playgroud)
更多信息 https://rxjs.dev/deprecations/writing-changes#throwerror
rxjs 5
或
throw response;
Run Code Online (Sandbox Code Playgroud)
要么
throw Observable.throw(response);
Run Code Online (Sandbox Code Playgroud)
小智 9
与rxjs 6
import { throwError } from 'rxjs';
throwError('hello');
Run Code Online (Sandbox Code Playgroud)
这是官方示例(发出数字 7,然后发出错误“哎呀!”):
import { throwError, concat, of } from 'rxjs';
const result = concat(of(7), throwError(new Error('oops!')));
result.subscribe(x => console.log(x), e => console.error(e));
Run Code Online (Sandbox Code Playgroud)
来自: https: //rxjs-dev.firebaseapp.com/api/index/function/throwError
归档时间: |
|
查看次数: |
60701 次 |
最近记录: |