Receiving data from an observable

1

I have a problem using an observable. While I'm inside the NgOinit method, when fetching the data, I get the array correctly and hedge in the class variable. However, when I try to access the data outside the subscribe, I get undefined in response. Does anyone know why this occurs?

@Component({
      moduleId: module.id,
      selector: 'operacao',
      templateUrl: './operacao.component.html',
      providers: [Operacao],
      styleUrls: ['./operacao.component.css']
    })
    export class OperacaoComponent implements OnInit {

      private _operacao: Operacao;
      private _operacoes: any[];


    public rows: Array<any> = [];
    private myserviceService: MyserviceService;
...


 constructor(myservice: MyserviceService) {
    this.length = 10;
    this.myserviceService = myservice;

  }
    ...

ngOnInit() {
 this.myserviceService.getOperacoes()
  .subscribe((operacao) => {
    this._operacoes = operacao; 
    //here i get the "right" value
     console.log(this._operacoes); 
    //Array(2) [Object, Object]
    //0:Object {id: 0, acao_id: 0, user_id: "1", …}
    //1:Object {id: 1, acao_id: 1, user_id: "1", …} 

myservice.ts

getOperacoes() {
      return this.http.get(this.url + 'operacoes').map(res => res.json());
}

When I try to access the data outside the observable, I get undefined.

console.log(this._operacoes);
    
asked by anonymous 20.11.2017 / 12:37

1 answer

1

The problem is that you are using the reserved word this to access the operations variable within the subscribe. This happens because in javascript, % scope% changes when you enter the block of this you created to subscribe to it.

To solve this problem, we need to link this from the scope of its main class to a variable and pass it into subscribe. To do this, simply change your function to:

ngOnInit() {
 let self = this;
 this.myserviceService.getOperacoes()
  .subscribe((operacao) => {
    self._operacoes = operacao; 
     console.log(self._operacoes);
  });
}

If you have only one line (an assignment, for example), you would not have to create a new block (so you would not create a new scope), so you can use the ngOnInit keyword as follows :

ngOnInit() {
 this.myserviceService.getOperacoes()
  .subscribe((operacao) => this._operacoes = operacao);
}

A third possibility is to bind a% of the class itself to treat the received data, as follows:

ngOnInit() {
 this.myserviceService.getOperacoes()
  .subscribe((operacao) => this.trataResposta(operacao));
}

trataResposta(resposta: any[]) {
  this._operacao = resposta;
  //Qualquer tratamento necessário
}
    
20.11.2017 / 13:21