【问题标题】:Angular two way binding of image not working as expected图像的角度双向绑定无法按预期工作
【发布时间】:2021-02-23 09:05:30
【问题描述】:

我有一个角度组件,它使用图像标签显示从 html 上的 websocket 获取的 base64 图像字符串。我每秒轮询一次 websocket 并尝试在页面上显示它。这是我的代码:

组件的html:

<div class="row">
    <div class= "video">
        <img [src]="_DomSanitizationService.bypassSecurityTrustUrl(getBase64Image())" style="margin-left:30%;width:800px;height:400px;">
    </div>
</div>

打字稿代码:

import { DomSanitizer } from '@angular/platform-browser';
import { io } from 'socket.io-client';

export class HelloComponent implements OnInit{
  messageText: string;
  messages: Array<any>;
  socket: any;
  subscription: Subscription;
  intervalId: any;
  image: any;

  constructor(public _DomSanitizationService: DomSanitizer ) {
  }

  ngOnInit(){
    this.getLatestFrame();
    this.intervalId = setInterval(this.getLatestFrame, 1000);
  }

  getLatestFrame(){
    this.socket = io(environment.websocket_url);
    this.socket.emit('hello', {
      msg: 'Client to server, can you hear me server?'
    });

    this.socket.on('frame', (data: any) => {
      this.image = data;
    });
  }

  ngOnDestroy() {
    clearInterval(this.intervalId);
  }

  getBase64Image(): string {
    return "data:image/png;base64, " + this.image;
  }
}

使用此代码,我可以看到 getLatestFrame() 每隔 1 秒就会被调用一次,就像我预期的那样。 getBase64Image() 也被调用,我可以每秒看到新的 base64 字符串,这意味着图像发生了变化,但是在 UI 上,我只能看到在 ngInit 期间加载的第一帧,之后没有任何变化。不明白为什么。

【问题讨论】:

标签: angular


【解决方案1】:

您可以通过调用ngOnInit() 方法在任何输入更改时重新渲染组件,因为它会重新渲染组件而无需重新加载页面。

getLatestFrame(){
    var _this = this;
    this.socket = io(environment.websocket_url);
    this.socket.emit('hello', {
        msg: 'Client to server, can you hear me server?'
    });

    this.socket.on('frame', (data: any) => {
        this.image = data;
        _this.ngOnInit();
    });
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-24
    • 1970-01-01
    • 2021-04-23
    • 1970-01-01
    • 2019-02-06
    • 1970-01-01
    相关资源
    最近更新 更多