首页 > 解决方案 > 从数据中获取值(Typescript)

问题描述

在我的代码中,我在 ngOnInit 中有这些行:

this.state.params.subscribe(
      (params: any) => {
        console.log("Estes sao os parametros: " + params['id']);
        if(params['id']){
          console.log("ID confirmado");
          this.data = this.cteDadosService.getCte(params['id']);
          this.data.subscribe(
              cte => {
                this.cte = cte.data[0].CTe[0] || [];
                this.idEmitente = cte.data[0].CTe[0].idEmitente; 
                console.log("CT-e:");
                console.log(this.cte);//show the content of this.cte correctly              
              },
            )
            this.data.subscribe(
              nf => {
                this.nf = nf.data[2].nf || [];
                console.log("NF:");
                console.log(this.nf);//show the content of this.nf correctly
              },
            this.data.subscribe(
              carga =>{
                this.carga = carga.data[1].carga || [];
                console.log("Carga:")
                console.log(this.carga);//show the content of this.carga correctly
              }
            )
            )

          }
        }
      )

其中 this.cte、this.nf 和 this.carga 是私有的,并且 any = []。

那么问题是:在函数“this.state.params.subscribe”之外,这些私有没有值。例如:

somefunction()
{
 console.log(this.cte);// show [] on console
 console.log(this.nf);// show [] on console
 console.log(this.carga);// show [] on console
}

我能做些什么来解决这个问题?

谢谢。

标签: javascriptangulartypescript

解决方案


您需要从 subscribe 函数内部调用 this.someFunction() ,因为它们是异步的并且异步获取值。


推荐阅读