Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

133
Views
Angular class variable loses value

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);
        });
    }
}
over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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.

One more alternative if you code in ECMA 6.0:

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);
        }
    });
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!