I am creating an Ionic application that works using token-based authentication. When a user authenticates an access token, it is stored in local storage.
My code then calls the provider for any data it needs (in this case, it pulls the Tutorials from the API).
In turn, this provider calls another provider that processes HTTP requests for my API. It effectively sets the required headers and initiates an HTTP request, and then returns a response back to the requesting provider.
All this works fine until I need to get the access token from the repository before making an HTTP request. It seems that accessing data from the repository is not instantaneous and uses syntax instead then.
It seems that when I call the provider from my code, it goes to the training provider, and then to the API provider. Then the code is launched and returned, but this happens before my application will be able to get what I need from the repository.
I tried to put everything in the request inside the thenmethod call storage.get, but this did not work.
Here is my requesting code:
this.trainingProgramme.get_programmes().subscribe((res) => {
loader.dismiss();
console.log(res);
});
What filters up to my supplier trainingProgramme:
get_programmes() {
let seq = this.api.get('training-programmes');
seq
.map(res => res.json())
.subscribe();
return seq;
}
Which, in turn, goes to my provider api:
export class Api {
base_url: string = 'https://******.com';
url: string = this.base_url + '/api/v1';
access_token: string;
constructor(
public http: Http,
private storage: Storage) {
storage.get('access_token').then((val) => {
console.log('Pulled access token from local storage', val);
this.access_token = val;
});
}
get(endpoint: string, params?: any) {
let headers = new Headers();
headers.append('Authorization', 'Bearer ' + this.access_token);
let options = new RequestOptions({ headers: headers });
return this.http.get(this.url + '/' + endpoint, options);
}
}
This does not lead to errors, but the headers sent:
Authorization: Bearer undefined
: , storage , HTTP , . storage HTTP-? then , subscribe s, .
1:
, , storage , , , HTTP-, then.
get(endpoint: string, params?: any) {
this.storage.get('access_token').then((val) => {
console.log('Pulled access token from local storage', val);
this.access_token = val;
let headers = new Headers();
headers.append('Authorization', 'Bearer ' + this.access_token);
let options = new RequestOptions({ headers: headers });
return this.http.get(this.url + '/' + endpoint, options);
});
}
:
Runtime Error
Uncaught (in promise):
TypeError: Cannot read property 'map' of undefined
TypeError: Cannot read property 'map' of undefined at TrainingProgramme.get_programmes
, , get , , .