0

I am using ionic 2 / angular 2.

I need to do a http request, but before I have to get a token using Ionic Storage.

I created a class ApiRequest for that

import {Http, Headers, RequestOptions} from '@angular/http';
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import { Storage } from '@ionic/storage';

@Injectable()
export class ApiRequest {

    access_token: string;

    constructor(private http: Http, public storage: Storage) {
        this.storage.get('access_token').then( (value:any) => {
            this.access_token = value;
        });
    }

    get(url) {
        let headers = new Headers({
            // 'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + this.access_token,
            'X-Requested-With': 'XMLHttpRequest'
        });
        let options = new RequestOptions({ headers: headers });

        return this.http.get(url, options)
            .map(res => res.json());

    }

}

Then I can call like that

apiRequest.get(this.URL)
        .subscribe(
            data => {
                this.element= data;
            },
            err => {
                console.log(JSON.stringify(err));
            });

My problem is, this.storage.get is asynchronous, http.get is asynchronous too, and I have to return http.get because I want to call subscribe outside the function.

In this case http.get is called before this.acess token received the value.

How Can I organize my code in that scenario?

Gabriel
  • 265
  • 3
  • 10
  • This might help ~ http://stackoverflow.com/questions/35498456/what-is-httpinterceptor-equivalent-in-angular2 – Phil Oct 03 '16 at 01:53

1 Answers1

2

This might work (not tried myself):

@Injectable()
export class ApiRequest {

    access_token: string;

    constructor(private http: Http, public storage: Storage) {
        this.storagePromise = this.storage.get('access_token').then( (value:any) => {
            this.access_token = value;
        });
    }

    get(url) {
        let headers = new Headers({
            // 'Content-Type': 'application/json',
            'Authorization': 'Bearer ' + this.access_token,
            'X-Requested-With': 'XMLHttpRequest'
        });
        let options = new RequestOptions({ headers: headers });

        return this.storagePromise.then(
           return token => this.http.get(url, options)
           .map(res => res.json());
        );
    }
}
apiRequest.get(this.URL)
    .then(observable => 
      observable.subscribe(
        data => {
            this.element= data;
        },
        err => {
            console.log(JSON.stringify(err));
        }
      );
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567