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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Update another component when Formik form changes(当Formik表单更改时更新另一个组件)
Formik validation isSubmitting / isValidating not getting set to true(Formik验证正在提交/isValiating未设置为True)
React Validation Max Range Using Formik(使用Formik的Reaction验证最大范围)
Validation using Yup to check string or number length(使用YUP检查字符串或数字长度的验证)
Updating initialValues prop on Formik Form does not update input value(更新Formik表单上的初始值属性不会更新输入值)
password validation with yup and formik(使用YUP和Formick进行密码验证)