Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

134
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda