javascript - http调用未在promise回调 Angular 2中触发

标签 javascript angular promise observable angular2-http

在我的 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/

相关文章:

angular - 如何聚焦具有 ngif 的 TextArea

javascript - 如何在 Angular 2 的同一组件中使用多个 ng-content?

angularjs - 单元测试,当 $http 没有被调用时等待 promise

javascript - 使用 $routeParams undefined 和 ngRepeat :dupes error

javascript - 用于 ui-select 多个的 Angularjs 验证

javascript - Yii2:如果出现任何 yii2 错误,如何使 Bootstrap 选项卡处于事件状态

javascript - mark.js 突出显示特定单词

javascript - 等待 promise 内的函数完成

javascript - 如果找到值,则返回解析为 bool 值 true 或 false 的 promise

Javascript - 延迟 Promise 解析