Cannot read property 'propostas_realizadas' of undefined - Angular 2

前端 未结 1 1865
死守一世寂寞
死守一世寂寞 2021-01-27 04:46

I have an application in Angular 2 in which I\'m trying to print some data on my console \"console.log(this.disputa.propostas_realizadas)\", however when I try to p

相关标签:
1条回答
  • 2021-01-27 05:32

    You are console logging the response before it has been assigned, this is an async operation.

    ngOnInit() : void{  
      this.route.params.subscribe(params =>{
      let id = params['id'];
      this.service
        .buscaPorId(id)
        .subscribe(disputa => {
          // executed sometimes later...
          this.disputa = disputa;
          console.log(disputa);
        },
        erro => console.log(erro));
      })
       // executed first
       console.log(this.disputa.propostas_realizadas);
    }
    

    Notice the comments in above code. To have your data available, you need to do it inside the subscription, so the following should work:

    ngOnInit() : void{  
      this.route.params.subscribe(params =>{
      let id = params['id'];
      this.service
        .buscaPorId(id)
        .subscribe(disputa => {
          this.disputa = disputa;
          console.log(disputa);
          // here!
          console.log(this.disputa.propostas_realizadas);
        },
        erro => console.log(erro));
      })
    }
    
    0 讨论(0)
提交回复
热议问题