简体   繁体   English

Ionic 3:带有 Observable 的离子存储

[英]Ionic 3: Ionic Storage with Observables

I have CustomerPage, CustomerService and AuthService.我有 CustomerPage、CustomerService 和 AuthService。

In need to pass an access_token from AuthService to CustomerService for http-get request.需要将 access_token 从 AuthService 传递给 CustomerService 以进行 http-get 请求。 AuthService and CustomerService are not working. AuthService 和 CustomerService 不起作用。

Please help me!请帮我!

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: is not working !!! AuthService:不工作!!!

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

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

To read async data and then make a request with it — use a switchMap operator读取异步数据,然后用它发出请求——使用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)
    )
  )
}

Note that fromPromise is now just from .请注意, fromPromise现在只是from

Hope this helps希望这可以帮助

you can use this:你可以使用这个:

this.local.get('access_token');

or else you can use these methods:否则你可以使用这些方法:

for setting the token:用于设置令牌:

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

for Getting the token:获取令牌:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM