0

I'm new at angular and I have the following problem

When assigning response value to the variable of my service, that variable is presented in the chorme console as undefined

But in the subscribe method http the variable is with the assigned value of the response.

I'm not understanding the problem

@Injectable() 
export class ControlService {

    permissao: string;

    constructor(
                private httpConnection: HttpConnection,
                private http: Http){}


    getControl(){
        if(localStorage.papel){

            this.buscar('desconto', 'todos');

            console.log('Permissão: ' + this.permissao);

    }

    buscar(desconto : string, todos : string){

        return this.http.get('http://localhost:8080' + "/" + aplicacao + "/" + nome)
            .subscribe((response) => {this.permissao = response.text(); console.log(this.permissao)});
    }   
}

the console.log inside busca method displays the value in the google chrome console, but the console inside the getControl method shows the value of the permissao variable as undefined

Ger
  • 583
  • 2
  • 13
  • 35

1 Answers1

0

this.buscar is an async operation, and your console.log statement inside getControl is called synchronously. So its called just after this.buscar('desconto', 'todos') line. However, in the meantime, buscar subscribe block has not been executed and is still waiting for get call to be resolved. Hence, you are getting undefined.

Vatsal
  • 2,068
  • 4
  • 21
  • 24
  • Thanks for the Vatsal answer, what would be the suggestion for me to have the value of my variable just after the fetch method buscar – Ger Sep 27 '18 at 19:59
  • If you're using the variable in your template, you could wrap the tags that use it with an *ngIf like:
    Then you should be able to use it inside the div as you would expect.
    – rrd Sep 27 '18 at 21:35