我是Ionic和Angular的新手,来自多年的.NET开发。我正在网上尝试一些例子,用Ionic 2构建登录原型。
我让WebAPI在后台工作,只需返回JSON的真或假,具体取决于传递的凭据是否正确。
我的身份验证提供程序看起来像这样:
public login(credentials) {
if (credentials.email === null || credentials.password === null) {
return Observable.throw("Please insert credentials");
} else {
this.result = this.http.post(this.CONST.APIUrl, JSON.stringify(credentials), new RequestOptions({headers: this.contentHeader})).map(res => res.json())
if (this.result)
{
this.currentUser = new User('Simon', 'saimon@devdactic.com');
}
return this.result;
}}
和登录页面看起来像这样:
public login() {
this.showLoading()
this.auth.login(this.registerCredentials).subscribe(allowed => {
if (allowed) {
setTimeout(() => {
this.loading.dismiss();
this.nav.setRoot(HomePage)
});
} else {
this.showError("Access Denied");
}
},
error => {
this.showError(error);
});
}
目前它总是记录下来的人。我知道这种情况正在发生,因为this.result总是有价值。但是,在允许用户登录之前,我如何检查从API返回的数据?
答案 0 :(得分:0)
您可以使用Observable.do为Observable创建副作用。
在登录功能中:
public login(credentials) {
if (credentials.email === null || credentials.password === null) {
return Observable.throw("Please insert credentials");
} else {
this.result = this.http.post(this.CONST.APIUrl,
JSON.stringify(credentials), new RequestOptions({headers: this.contentHeader}))
.map(res => res.json())
.do(userData=>{
//check userData and set current user
this.currentUser = new User('Simon', 'saimon@devdactic.com');
return userData;//make sure to return the value to subscribe
});
return result;
}}