Angular 2 - 从承诺中返回 HTTP

Angular 2 - Return HTTP from inside a promise(Angular 2 - 从承诺中返回 HTTP)
本文介绍了Angular 2 - 从承诺中返回 HTTP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

在我的 api 服务中的每个 http 调用之前,我想检查我的本地存储是否有访问令牌,然后在我拥有它后进行调用.看起来是这样的

Before each http call in my api service I want to check my local storage for an access token, then make the call once I have it. It looks like this

read(endpoint,params?) {

    var url: string = this.authService.apiUrl + endpoint, 
        headers: Headers = new Headers(),
        queryString: URLSearchParams = new URLSearchParams();

    this.sessionService.getToken()
      .then((value) => {

        queryString.set('access_token', value);

        headers.append('Content-Type', 'application/json; charset=utf-8');

        return this.http.get(url,{
          headers: headers, 
          search: queryString
        })
        .map(res => res.json())

      });


  }

在我的组件中,我会有类似的东西

And in my component I would have something like

  getData() {
    this.apiService.read('some endpoint')
      .subscribe(
        res => console.log(res),
        error => this.logError(error)
      )
  }

这一直有效,直到我在检查本地存储后将 http 调用放入 .then 中.所以我认为它现在嵌套不正确.

This was working until I put the http call inside of the .then after checking the local storage. So I think it is now nested incorrectly.

解决这个问题的正确方法是什么?在此设置中,是否有更有效的方式从本地存储中获取我的令牌?注意:我使用的是 Ionic 2,它有自己的功能来检查返回承诺的本地存储.

What is the correct way to appraoch this? And is there perhaps a more efficent way to grab my token from local storage in this set up? NOTE: I am using Ionic 2 which has its own function for checking local storage which returns a promise.

任何建议都会很棒.

谢谢.

推荐答案

您必须将 http observable 转换为 promise 或将 promise 转换为 observable.

You will have to convert the http observable to a promise or convert promise to an observable.

可观察到的承诺:

read(endpoint,params?) {

    var url: string = this.authService.apiUrl + endpoint, 
        headers: Headers = new Headers(),
        queryString: URLSearchParams = new URLSearchParams();

    return this.sessionService.getToken() //return the outer promise
      .then((value) => {

        queryString.set('access_token', value);

        headers.append('Content-Type', 'application/json; charset=utf-8');

        return this.http.get(url,{
          headers: headers, 
          search: queryString
        })
        .map(res => res.json()).toPromise() //use Observable.toPromise

      });


  }

调用使用

this.apiService.read('some endpoint').then((data)=>{}).catch(err=>{})

对 Observable 的承诺:

Promise to Observable:

read(endpoint,params?) {

    var url: string = this.authService.apiUrl + endpoint, 
        headers: Headers = new Headers(),
        queryString: URLSearchParams = new URLSearchParams();

    return Observable.fromPromise(this.sessionService.getToken())//convert to Promise and return chain.
      .switchMap((value) => {//use Observable.switchMap to move to second observable

        queryString.set('access_token', value);

        headers.append('Content-Type', 'application/json; charset=utf-8');

        return this.http.get(url,{
          headers: headers, 
          search: queryString
        })
        .map(res => res.json())

      });


  }

RXJS 5.5 开始:

对 Observable 的承诺:

Promise to Observable:

read(endpoint,params?) {

    var url: string = this.authService.apiUrl + endpoint, 
        headers: Headers = new Headers(),
        queryString: URLSearchParams = new URLSearchParams();

    return fromPromise(this.sessionService.getToken())//import {fromPromise } from "rxjs/observables/fromPromise";
     .pipe(
      switchMap((value) => {//import {switchMap} from 'rxjs/operators/switchMap';

        queryString.set('access_token', value);

        headers.append('Content-Type', 'application/json; charset=utf-8');

        return this.http.get(url,{
          headers: headers, 
          search: queryString
        })
      });
     );

  }

这篇关于Angular 2 - 从承诺中返回 HTTP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!

相关文档推荐

How do I can get a text of all the cells of the table using testcafe(如何使用 testcafe 获取表格中所有单元格的文本)
node_modules is not recognized as an internal or external command(node_modules 未被识别为内部或外部命令)
How can I create conditional test cases using Protractor?(如何使用 Protractor 创建条件测试用例?)
PhantomJS and clicking a form button(PhantomJS 并单击表单按钮)
Clicking #39;OK#39; on alert or confirm dialog through jquery/javascript?(在警报上单击“确定或通过 jquery/javascript 确认对话框?)
QunitJS-Tests don#39;t start: PhantomJS timed out, possibly due to a missing QUnit start() call(QunitJS-Tests 不启动:PhantomJS 超时,可能是由于缺少 QUnit start() 调用)