在我的角度应用程序中,我有以下登录方法:
login(username, password): Observable<User> {
let data = new URLSearchParams();
data.append('username', username);
data.append('password', password);
const url = 'https://server.com/some-endpoint/';
return this.http.post(url, data)
.map(res => res.json())
.map(json => throwUnlessLoginSuccessful('properties', json))
.map(json => new User().deserialize(json));
}
所以我想在回复中做以下事情:
这是我的throwUnlessLoginSuccessful
方法:
private throwUnlessLoginSuccessful(string: string, json: Object) {
if (Number(json["responseCode"]) > 0) {
console.warn("Sign in failed");
return Observable.throw(new Error(json['responseCodeMessage']));
}
return json;
}
这就是我在UI中使用登录服务的方式:
this.loginService.login(this.login.username, this.login.password).subscribe(
user => {
this.session.login(this.login.username);
console.log(`Signed in with ${user.username}`);
this.navCtrl.setRoot(TabsPage);
},
err => {
console.log(`Sign in failed $\{err}`)
this.loading.dismiss();
console.log(err);
},
() => console.log('Completed')
);
username
无效的错误。为什么&#34;完成&#34;没有第一次执行,如果我用错误的凭据重复登录,为什么行为会有所不同?
答案 0 :(得分:3)
您应该throw new Error(...)
而不是返回Observable.throw(new Error(...))
。目前,您只是将错误结果映射到Observable
。