I am facing an issue where I need to retrieve two values stored in Ionic storage, but the values are retrieved asynchronously causing the request to happen before the values are fetched.
The values for Auth and url are stored in Ionic storage.
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import 'rxjs/add/operator/map';
import {Headers} from '@angular/http';
import { Storage } from '@ionic/storage';
/*
Processor for SeasonService provider.
Visit https://angular.io/docs/ts/latest/guide/dependency-injection.html
for more details on providers and Angular 2 DI.
*/
@Injectable()
export class SeasonService {
Auth;
url;
constructor(public http: Http, public storage: Storage) {
console.log('Inside SeasonService constructor');
this.storage.get('Auth').then((Auth) => {
console.log('Retrieved Auth value is', Auth);
this.Auth = Auth;
} );
this.storage.get('url').then((url) => {
console.log('Retrieved url value is', url);
this.url = url;
} );
}
public getSeasonList() {
console.log('Season Auth value is', this.Auth);
console.log('Season url value is', this.url);
const headers: Headers = new Headers();
headers.append('Authorization', 'Basic ' + this.Auth);
headers.append('Content-Type', 'application/json');
return (this.http.get('http://' + this.url +'/Windchill/servlet/rest/rfa/instances?module=SEASON',
{headers: headers}).
map((response: Response) => response.json()));
}
}
This is how the Output appears:
Here
auth-service.ts:49 Headers {_headers: Map(2), _normalizedNames: Map(2)}
auth-service.ts:77 There
season-service.ts:19 Inside SeasonService constructor
season-service.ts:34 Season Auth value is undefined
season-service.ts:35 Season url value is undefined
season-service.ts:22 Retrieved Auth value is d2NhZG1pbjp3Y2FkbWlu
season-service.ts:27 Retrieved url value is 192.168.146.52
auth-service.ts:79 Your CSRF token is laxYnd5XE6d/r+W655087+8dY5Irxc7do94fxLgvY5ImgNeIwsgI1bYaQdAzxZDM5sMZsqgbXppFntGDoJhrq+puJJROnN+N1MEcy7d4Js8ozs7Oxpwfpe0zRvcIktg=
auth-service.ts:82 Your Authorization key is d2NhZG1pbjp3Y2FkbWlu
auth-service.ts:85 Your URL is 192.168.146.52