在我的 Angular 2 项目中,我调用这个函数来获取一些数据:
this.http.getfromgraphql()
.map((response: Response) => response.json())
.subscribe(
(data) => {
console.log(data);
});
这会触发如下所示的 getfromgraphql 函数,但在我进行该调用之前,我必须在 checkaccesstokenvalidity 中检查访问 token 是否仍然有效,我在那里设置了一些变量并解析了该函数。
控制台登录“然后”,但我的 http 帖子不会触发。
这是为什么?
此外,我确信有更好的方法可以做到这一点,但对于我的生活我无法弄清楚,非常感谢更好的解决方案
checkAccessTokenValidity() {
let headers = new Headers();
headers.append( 'Content-Type', 'application/x-www-form-urlencoded' );
let options = new RequestOptions({ headers: headers });
// if(!this.access_token) {
return new Promise((resolve, reject) => {
this.http.post(this.URL + 'oauth/token', this.authentication, options)
.subscribe(function(response) {
this.authObj = response.json();
this.expirationDate = new Date();
this.expirationDate.setSeconds(this.expirationDate.getSeconds() + this.authObj.expires_in);
console.log(this.authObj, this.expirationDate);
},
error => console.log("Error: ", error),
function() {
console.log('resolving');
resolve();
});
});
// }
}
getfromgraphql() {
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
// headers.append('Authorization', 'Bearer ' + this.access_token );
let options = new RequestOptions({ headers: headers });
this.checkAccessTokenValidity().then(function() {
console.log('in then');
//noinspection TypeScriptValidateTypes
return this.http.post(this.URL + '/api/v1/graphql', this.query, options);
});
}
最佳答案
第 1 点:
请勿在您的任何回调中使用 function(){}
。假设您使用的是 Typescript(或 ES6),您没有使用 lexical
this。您所有的 this
都将引用内部范围。你会得到很多未定义的。使用粗箭头符号 ()=>{}
。
第 2 点:
既然您已经在所有方法中使用了 Observables
,请继续使用它们(响应式编程),除非必要,否则不要使用 Promise
。
在您的getfromgraphql()
方法中,只需使用flatMap()
。和promise中的.then()
是一样的。
此外,在解决错误时,如果需要,只需执行 .catch()
即可。 Observables 会将错误传播给最高级别的调用者。
checkAccessTokenValidity() {
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
let options = new RequestOptions({headers: headers});
return this.http.post(this.URL + 'oauth/token', this.authentication, options)
.map(response => {
this.authObj = response.json();
this.expirationDate = new Date();
this.expirationDate.setSeconds(this.expirationDate.getSeconds() + this.authObj.expires_in);
console.log(this.authObj, this.expirationDate);
})
.catch(error=>{
console.log(error);
return Observable.empty();
})
}
getfromgraphql() {
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded');
// headers.append('Authorization', 'Bearer ' + this.access_token );
let options = new RequestOptions({headers: headers});
return this.checkAccessTokenValidity().flatMap(()=>{
console.log('in then');
//noinspection TypeScriptValidateTypes
return this.http.post(this.URL + '/api/v1/graphql', this.query, options);
})
}
关于javascript - http调用未在promise回调 Angular 2中触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44966788/