我正在订阅以下活动清单
userService.createUser(this.form).subscribe((user)=>{ this.user = user })
服务方法如下所示......
createAccount(user) {
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http
.post(
'/api/accounts',
JSON.stringify(user),
{headers}
)
.map(res => res.json())
.map((res) => {
if (res['account']) {
this.authService.isLoggedIn = true;
this.loggedIn.next(true);
this.userData = res["account"];
return res;
} else {
this.authService.isLoggedIn = false;
}
});
}
我需要在createUser中以某种方式添加这样的调用,以在用户完成之前检查用户是否存在...
checkForDups(user){
return this.http
.get('/api/checkfordups/'+user.email)
.map(res => res.json())
.map((res) => {
if (res>0) {
//user account exists...
return {'message' : 'User account exists!'};
} else {
return true;
}
});
}
我试过了......
createAccount(user) {
if( this.checkForDups(user)){
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http
.post(
'/api/accounts',
JSON.stringify(user),
{headers}
)
.map(res => res.json())
.map((res) => {
if (res['account']) {
this.authService.isLoggedIn = true;
this.loggedIn.next(true);
this.userData = res["account"];
return res;
} else {
this.authService.isLoggedIn = false;
}
});
}else{
return {"message": "duplicate account found"};
}
}
但它无法正常工作。对更好的方法有任何想法吗?
答案 0 :(得分:0)
在上一个代码中,您可以订阅checkForDups而不是在if语句中调用它。像这样:
createAccount(user) {
this.checkForDups(user)
then.(result => {
if( this.checkForDups(user)){
let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http
.post(
'/api/accounts',
JSON.stringify(user),
{headers}
)
.map(res => res.json())
.map((res) => {
if (res['account']) {
this.authService.isLoggedIn = true;
this.loggedIn.next(true);
this.userData = res["account"];
return res;
} else {
this.authService.isLoggedIn = false;
}
});
}else{
return {"message": "duplicate account found"};
}
});
}
在checkForDups中,不要忘记在http调用后调用.toPromise()
:
import 'rxjs/add/operator/toPromise'; // import the .toPromisse method here
...
checkForDups(user){
return this.http
.get('/api/checkfordups/'+user.email)
.map(res => res.json())
.map((res) => {
if (res>0) {
//user account exists...
return {'message' : 'User account exists!'};
} else {
return true;
}
})
.toPromise(); // do not forget this so you would not be able to call the `.then(...)` method inside createAccount
}