【问题标题】:Ionic 3: Ionic Storage with ObservablesIonic 3:带有 Observables 的 Ionic 存储
【发布时间】:2019-03-26 09:10:06
【问题描述】:

我有 CustomerPage、CustomerService 和 AuthService。

需要将一个 access_token 从 AuthService 传递给 CustomerService 以获取 http-get 请求。 AuthService 和 CustomerService 不起作用。

请帮帮我!

谢谢。

客户页面:

this.customerService.getCustomersDashboard()
      .subscribe(....)

客户服务:

getCustomersDashboard(): Observable<any> {
      var url = "......";
    let authHeader = this.authservice.getAuthHeaders();  // HttpHeader with access_token

    return this.http.get(url, { headers: authHeader }).pipe(
      map((resp: Response) => {
        let response = this.extractData(resp);
        return response;
      }));

身份验证服务: 不工作!!!

 getAuthHeaders(){
    const authtoken = Observable.fromPromise(this.storage.get(`access_token`));

    return new HttpHeaders({ 'authorization': authtoken });  // => **not working**
  }

【问题讨论】:

  • 您的存储 API 承诺是否基于?如果它是异步的——你不能只将它传递给标题。使用switchMap 从存储中读取值并切换到http-get。如果它是同步的——那么你不需要fromPromise
  • 离子存储是基于承诺的!你能提供switchMap的伪代码吗?谢谢

标签: angular ionic-framework rxjs


【解决方案1】:

要读取异步数据并然后发出请求 - 使用 switchMap 运算符

getCustomersDashboard() {
  const url = '//...';
  // read data from storage
  return from(this.storage.get('access_token')).pipe(
    // now switch to a http-get request
    switchMap(access_token => {
      // make a HttpHeaders from it
      const headers = new HttpHeaders({ 'authorization': access_token });
      return this.http.get(url, { headers })
    }),
    // here you'll have your request results
    map(response =>
      this.extractData(response)
    )
  )
}

请注意,fromPromise 现在只是 from

希望对你有帮助

【讨论】:

  • 不工作,“'void'类型的'this'上下文不可分配给'Observable'类型的方法'this'
  • @Alexander,很难理解这个错误的含义。这是什么线?
  • switchMap中的所有行
  • @Alexander,嗯,我不确定为什么 TS 会在那里抱怨(除了我拼写错误的 access_token)。你能为此创建一个堆栈闪电战吗?它是一个伪代码。
  • @Alexander,你在本地安装的是什么版本的rxjs?如果是&lt;5.5,则使用.switchMap().map() 而不是.pipe( switchMap(), map() )
【解决方案2】:

你可以使用这个:

this.local.get('access_token');

否则你可以使用这些方法:

用于设置令牌:

this.local = new Storage(LocalStorage);
this.local.set("YourTokenValue", this.access_token);

获取令牌:

toCheckStatus();
function toCheckStatus()
{
    self.local = new Storage(LocalStorage);
    self.local.get('access_token').then((token) => 
    {
        console.log("token", token);
    });
}

【讨论】:

    猜你喜欢
    • 2018-03-10
    • 1970-01-01
    • 1970-01-01
    • 2019-12-10
    • 1970-01-01
    • 2018-03-19
    • 1970-01-01
    • 2018-04-23
    • 2018-02-13
    相关资源
    最近更新 更多