【发布时间】:2017-06-12 12:54:28
【问题描述】:
我在名为 accountManager 的服务中有一个函数,它返回如下所示的承诺:
这个 promise 上的 .then() 触发并打印出预期的响应。
signIn(email:String,password:String):Promise<any>{
return this.http.post('http://localhost:3000/api/signin',JSON.stringify({
"email": email,
"password": password
}),{headers: this.headers})
.toPromise()
.then(res => {
//**This is defined**
console.log(res);
})
}
当我在另一个使用此登录方法的类中时,就会出现问题。承诺中的响应现在为空。当我从函数本身中省略承诺时,返回的承诺的 .then() 具有响应的值。
if (this.loginForm.valid === true){
this.accountManager.signIn(this.email,this.password)
.then(response =>{
//**This .then has an undefined response when added on to the promise returned from the signIn function.**
let body = JSON.parse(response._body)
if (body.payload.success === true){
this.router.navigate(['/']);
}else{
this.signInError = true;
}
})
.catch(error=>{
this.signInError = true;
})
有谁知道为什么当 promise 被返回时 promise .then() 包含一个值,但 return 给出的 promise 在它的 .then() 中没有值?如果有什么令人困惑的地方,我很乐意澄清。谢谢:)
【问题讨论】:
-
在
console.log通话后您没有返回res。 -
但是我不能返回它,因为我已经返回了函数,对吧?
-
不,这是不对的。在 .then 回调中返回与在封闭函数中返回无关 - 从当前函数返回返回
-
您的问题标题具有误导性 - 两个
.then都被调用,否则您不会知道第二个中的响应未定义。那么 -
感谢您的帮助!
标签: javascript angular typescript promise rxjs