Alexander
Alexander

Reputation: 13

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**
  }

Upvotes: 1

Views: 1868

Answers (2)

kos
kos

Reputation: 5364

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

Upvotes: 1

Pupinder Singh
Pupinder Singh

Reputation: 25

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

Upvotes: 0

Related Questions