【发布时间】:2017-07-07 09:05:31
【问题描述】:
在我的 Angular 2 项目中,我进行了这个调用以获取一些数据:
this.http.getfromgraphql()
.map((response: Response) => response.json())
.subscribe(
(data) => {
console.log(data);
});
这会触发下面显示的 getfromgraphql 函数,但在我进行调用之前,我必须检查访问令牌在 checkaccesstokenvalidity 中是否仍然有效,我在那里设置了一些变量并解析了函数。
控制台登录“然后”,但我的 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);
});
}
【问题讨论】:
-
getfromgraphql ()这个函数你是怎么使用的? -
我使用 this.http.getfromgraphql() 从某个组件调用 getfromgraphql 然后该函数从 checkaccesstokenvalidity() 获取一个新的访问令牌,之后它向端点 /api/v1/graphql 发布消息,但是不会触发。
标签: javascript angular promise observable angular2-http