Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

136
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda