繁体   English   中英

Promise 中的 Angular 绑定在 ngOnInit 中不起作用

[英]Angular binding in Promise not work in ngOnInit

In Angular, I use a simple function that return a Promise and in 'then' function I change src of an Img html tag. 当我从 NgOnInit(或从 onclick)调用此 function 时,html 将不会更新,直到我通过再次单击某些内容来强制重新加载内容。 但 colsole.log 工作。

  click1() {
    this.loadCaptcha();
  }

  ngOnInit(): void {
    this.loadCaptcha();
  }

  loadCaptcha() {
    this.apiService.getCaptcha()
      .then((data) => {
        this.image = 'http://....' + data.id;
        console.log(data);
      });
  }
<img [src]='image' (click)="click1()" />

试试这个使用 DomSanitizer

 constructor(private sanitizer: DomSanitizer) { }
 
  ngOnInit() {
  this.apiService.getCaptcha()
      .then((data) => {
        let objectURL = 'data:image/jpeg;base64,' +  data.id;
        this.image  =this.sanitizer.bypassSecurityTrustUrl(objectURL);
        console.log(data);
      });
       
  }
}

希望有用

我解决了这个问题,问题是 Metronic 模板中存在禁用数据绑定的代码行。 通过禁用 changeDetection 修改,绑定再次起作用。

changeDetection: ChangeDetectionStrategy.OnPush,

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM