【问题标题】:How to use a variable outside the promise如何在承诺之外使用变量
【发布时间】:2018-02-26 21:17:57
【问题描述】:

所以我的离子存储中有一个授权令牌,我必须通过 http 请求传递它,但我似乎无法从 storage.get.then 承诺中获取值。

  getProducts(){
    let headers = new Headers(); 
    this.token= this.storage.get('Authorization').then((value)=>{
       this.token= value;
      return this.token; 
     });
     headers.append("Authorization",this.token);

    return this.http.get('https://vjtest.cobold.xyz/vapi/public/api/products',{headers: headers})
      .map(res=> res.json());

  }

【问题讨论】:

  • @wolverine 如果我将 http.get 放在里面,我会在订阅部分出错,因为 http.get return 不会从 getProduct 返回产品值//对不起,用文字表达不好跨度>

标签: angular ionic2 ionic3


【解决方案1】:

由于 Promise 是异步的,你必须等待响应,然后调用第二个请求。

getProducts(){
     return this.storage.get('Authorization').then((value)=>{
       this.token= value;
       return this.sendReq(this.token)
     });
}

sendReq(token){
      let headers = new Headers();       
      headers.append("Authorization",token);
      return this.http.get('https://vjtest.cobold.xyz/vapi/public/api/products',{headers: headers})
      .map(res=> res.json());
}

【讨论】:

  • 谢谢,您的代码是有意义的,虽然我遇到了这个错误,知道为什么吗? "Promise>" 类型上不存在属性 'subscribe'
  • 您必须订阅 HTTP 获取请求才能访问请求。
【解决方案2】:

您可以返回 http 请求(这将是一个 Observable)并订阅您的函数, 或者您在订阅请求本身后对其进行操作:

this.http
.get('https://vjtest.cobold.xyz/vapi/public/api/products',{headers: headers})
.subscribe(data => {
  //manipulate what the request returned here
});

【讨论】:

  • 我不是在处理数据,我只是在返回它。我正在尝试从离子存储中获取令牌并将其放入标头进行身份验证。
  • 那你就不用映射了。这取决于调用它的人来映射和操作它。
【解决方案3】:

尝试使用async函数。

getToken() {
   return this.storage.get('Authorization');
}

async getProducts(){
  this.token = await getToken();
  let headers = new Headers(); 
  headers.append("Authorization",this.token);
  return his.http.get('https://vjtest.cobold.xyz/vapi/public/api/products',headers: headers}).map(res=> res.json());

}

【讨论】:

  • @MayankSingh 尝试删除 function 关键字,参考更新后的答案
猜你喜欢
  • 2016-09-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-07-07
  • 2019-11-05
  • 2020-01-10
  • 2019-11-11
相关资源
最近更新 更多