简体   繁体   中英

Ionic Storage returning undefined the first time

I have a storage set to access_token and when i get it to return the first time i fails

PROVIDER:

getLayMinisters(){
   console.log(this.access_token);
   return this.http.get(
     this.api.url() + '/faith-leader/' + 'lay-ministers',
     {
       headers: new Headers({ "Authorization": "Bearer " + this.access_token })
     }
   )
   .map(
     response => response.json()
   );
}

This is the constructor for this file

access_token: any;
layMinister_id: string;

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

This is in my page

getLayMinisters(){
    this.layMinisterProvider.getLayMinisters().subscribe(
      data => {
        this.layMinisters = data;
      }
    );
}

This is above it

layMinisters = [];

constructor(
    public navCtrl: NavController, 
    public navParams: NavParams,
    public layMinisterProvider: LayMinisterProvider,
    public alertCtrl: AlertController
) {}

ionViewDidLoad() {
    this.getLayMinisters();
}
ionViewWillEnter() {
    // this.getLayMinisters();
}

When the page first runs it return the console.log(this.access_token) returns as undefined and then i get the error of the api not responding. But when i click on the link again to open the page it runs it fine and prints the access_token and runs the api call and prints all the data

When you call getLayMinisters() the access_token is undefined because these task are asynchronous, so when you do http.get probably this.storage.get() is not finished because It's a promise, if you code in http.get function

setTimeout(()=>{
  console.log(this.access_token)
},1000)

Maybe with 1000ms probably will print it (it depends of the storage.get() promise response time).

To solved it you can create a function in layMinisterProvider:

getToken(){
    return this.storage.get('access_token')
}

and in the page:

getLayMinisters() {
    if(!this.layMinisterProvider.access_token){
        this.layMinisterProvider
        .getToken()
        .then((access_token) => {
            this.layMinisterProvider.access_token = access_token;
            this.getData();
        })
    }else{
        this.getData();
    }
}
getData(){
    this.layMinisterProvider
                .getLayMinisters()
                .subscribe(data => {
                    this.layMinisters = data;
                });
}

Remember the provider must has access_token as public.

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