离子3:具有可观察物的离子存储

时间:2019-03-26 09:10:07

标签: angular ionic-framework rxjs

我有CustomerPage,CustomerService和AuthService。

需要将AuthService的access_token传递给CustomerService以获得http-get请求。 AuthService和CustomerService无法正常工作。

请帮助我!

Thnx。

CustomerPage:

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

CustomerService:

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;
      }));

AuthService: 不起作用!!!

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

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

2 个答案:

答案 0 :(得分: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

希望这会有所帮助

答案 1 :(得分:0)

您可以使用此功能:

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);
    });
}