Using Angular2, I have an http.get as follows:
this.http.post('http://localhost/Authenticated/Token', loginData, options).subscribe(function (data) {
console.log(JSON.stringify(data, null, 4));
if (data.status === 200) {
this.response = data.json();
this.access_token = this.response.access_token;
alert(this.access_token);
}
});
The value of this.access_token is being set correctly at runtime. But it loses value once the method is over. I am trying to use it somewhere else in a method but it says undefined.
EDIT:
Here is the method that is attached to a trigger on a button, that I call after I see the response from the previous method:
getBlogEntries() {
alert(this.access_token);
let headers = new Headers();
headers.append('Authorization', 'Bearer ' + this.access_token);
let options = new RequestOptions({
headers: headers
});
if (this.access_token) {
this.http.get('http://localhost/Authenticated/BlogEntries/', options).subscribe(result => {
this.blogEntries = result.json().Data;
console.log(this.blogEntries);
});
}
}
Try below code:
this.http.post('http://localhost/Authenticated/Token', loginData, options).subscribe(function (data) {
console.log(JSON.stringify(data, null, 4));
if (data.status === 200) {
this.response = data.json();
this.access_token = this.response.access_token;
alert(this.access_token);
}
}.bind(this));
It should resolve your issue.
this.http.post('http://localhost/Authenticated/Token', loginData, options).subscribe((data) => {
console.log(JSON.stringify(data, null, 4));
if (data.status === 200) {
this.response = data.json();
this.access_token = this.response.access_token;
alert(this.access_token);
}
});