Reputation: 321
I have an angular component that displays a base64 image string got from websocket on the html using the image tag. I poll the websocket every second and try to display it on the page. Here is my code:
html of component:
<div class="row">
<div class= "video">
<img [src]="_DomSanitizationService.bypassSecurityTrustUrl(getBase64Image())" style="margin-left:30%;width:800px;height:400px;">
</div>
</div>
the typescript code:
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;
}
}
With this code, I can see the getLatestFrame()
is being called every 1 second like I intended it to. The getBase64Image()
is also being called and I can see the new base64 string on every second meaning the image has changed but however on the UI, I can see the first frame only that got loaded during the ngInit only and no change after that. Can't understand why.
Upvotes: 0
Views: 378
Reputation: 385
You can re-render the component on any input change by calling the ngOnInit()
method as it re-renders the component without reloading the page.
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();
});
}
Upvotes: 1