【问题标题】:Angular IO: Return of promisesAngular IO:承诺的回报
【发布时间】:2018-10-15 10:12:41
【问题描述】:

我的系统有问题。

基本上,我有一个实体:

import { Produto } from "./produto.model";
import { Empresa } from "./empresa.model";
import { Mensagem } from "./mensagem.model";

export class Nfe{

    public codNfe: number;
    public numeroNfe: number;
    public dataEmissao: Date;
    public valorTotal: number;
    public empresa: Empresa;
    public produtos: Array<Produto>;
    public mensagens: Mensagem;

    constructor(){};
}

还有一项服务:

  constructor(private http: Http) { }

      public getNFE(numero: string): Promise<Nfe>{
        return this.http.get(`${URL_API}nfe?numeroNfe=${numero}`)
          .toPromise()
          .then((response: any) => {
            return response.json()
          });
      }

还有一个观点:

export class ExibirNfeComponent implements OnInit {

  public nfe: Nfe;
  constructor(private service: NfeService) { 

  }

  ngOnInit() {
    this.service.getNFE('26180406057223028939650050000133071050336085')
    .then((nfe: Nfe) => {
      this.nfe = nfe;
    })
  }

}

<div class="row">
  <div class="col-sm-2">Id: {{nfe.codNfe}}</div>
</div>

当我调用我的屏幕时,我收到此错误:

ERROR TypeError: Cannot read property 'codNfe' of undefined

我认为发生这种情况是因为服务需要一些时间来响应。我需要一种方法让视图等待我的对象变满。

我该怎么做?

更新 1

我放了一些控制台日志:

  ngOnInit() {
    console.log('Begin OnInit')
    console.log(this.nfe)
    this.service.getNFE('26180406057223028939650050000133071050336085')
    .then((nfe: Nfe) => {
      this.nfe = nfe;
      console.log(this.nfe)
    });
    console.log('End OnInit');
  }

查看结果: enter image description here

【问题讨论】:

    标签: angular promise angular-promise


    【解决方案1】:

    在定义之前,您在模板中使用了 nfe 变量。

    {{nfe.codNfe}}
    

    这就是信息告诉你的。您必须在使用前进行检查。通过添加? 有一个快捷方式。

    把那部分改成

    {{nfe?.codeNfe}}
    

    问号将检查 nfe 是否未定义或为空,如果不是,则仅访问 codeNfe。

    【讨论】:

    • 但是现在,我还有其他问题。我的变量没有在屏幕上更新。
    • 您确定变量已加载吗?在 then 块中添加控制台日志语句。
    • 是的,我愿意。我将使用控制台结果更新问题。
    • 如果服务有任何机会返回相同的对象(即使具有修改的属性),那么将不会检测到更改,假设您有 ChangeDetectionStrategy.OnPush。如果是这种情况,您必须注入 ChangeDetectorRef 并在其上调用 .detectChanges() 或 .markForCheck。
    【解决方案2】:

    我发现了问题。 这只是我的 JSON 框架。 该结构是一个矩阵,我的应用程序接收到一个对象。

    感谢一切

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-02
      • 1970-01-01
      • 2023-03-26
      • 1970-01-01
      • 2019-04-21
      • 2015-11-04
      • 1970-01-01
      • 2018-10-03
      相关资源
      最近更新 更多