【问题标题】:how to append data coming from socket io to angular html如何将来自套接字 io 的数据附加到角度 html
【发布时间】:2017-12-15 19:47:45
【问题描述】:

我有一个套接字程序,它列出并提供日志数据。 套接字正在发送正确的数据,因为在控制台中我得到了正确的数据。

这是我的代码

export class RoboLogComponent implements OnInit {
dataToShow:any
@ViewChild('dataContainer') dataContainer : ElementRef;

loaddata(data:String) {
    this.dataContainer.nativeElement.innerHtml =data
}
ngOnInit():void{
console.log("I am triggering")
let socket=io('http://localhost:9999')
socket.on('send-log-data',function(data){
    console.log(data) //here it is displaying correct value emitted from socket
    this.dataContainer.nativeElement.innerHtml =data //but is not getting reflected
})
}
}

在 html 中我已将其定义为追加。

<div #dataContainer></div>

此处来自套接字的数据正常,但没有反映到 ui。 在控制台中打印的是正确的值。

实际上我的用例是我的后端代码之一连续生成html格式的日志,我需要在web ui中显示日志

【问题讨论】:

    标签: javascript angular reactjs sockets socket.io


    【解决方案1】:

    经过大量研究后,我终于得到了答案。 我自带的解决方案

    export class RoboLogComponent implements OnInit,AfterViewInit,OnDestroy {
     dataToShow:string="lets see if i am coming"
     socket:any
    
    loaddata(data:any) {
        console.log("chcking")
        this.htmlToadd =this.htmlToadd+"<br>"+data
    }
    ngOnInit():void{
        this._labService.streamLogs().subscribe(data => 
    this.socket=io('http://localhost:9999')
    }
    
    
    ngAfterViewInit(){
    this.socket.on('send-log-data',function(data){
                    this.loaddata(data)                
    }.bind(this))
    }
     ngOnDestroy(){
    this.socket.disconnect()
    }
    
    }
    

    在html文件中添加

    <div class="abc" [innerHtml]="htmlToadd | sanitizeHtml" *ngIf='htmlToadd'></div>
    

    这里 sanitizeHtml 管道只是用来绕过动态加载的 html 内容的安全检查。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-10-27
      • 2016-11-20
      • 2018-08-12
      • 2019-05-13
      • 1970-01-01
      • 1970-01-01
      • 2019-10-17
      相关资源
      最近更新 更多