简体   繁体   中英

Ionic 3: Ionic Storage with Observables

I have CustomerPage, CustomerService and AuthService.

In need to pass an access_token from AuthService to CustomerService for http-get request. AuthService and CustomerService are not working.

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 !!!

 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

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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