图像的Angular双向绑定没有按预期工作



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

component:

<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期间加载,之后没有变化。我不明白为什么。

您可以通过调用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();
});
}

最新更新