简体   繁体   English

使用接收值动态更改 Angular Label

[英]Change Angular Label Dynamically with Received Value

I am working on Angular - Node websockets, scenario is when the button is clicked, it will be sending a request to server and get data and update the received data on client-side.我正在研究 Angular - 节点 websockets,场景是单击按钮时,它将向服务器发送请求并获取数据并在客户端更新接收到的数据。 but it is not changing as per.但它并没有改变。 code is below.代码如下。

Label on component HTML Label 在组件 HTML

<h2>{{iSpeed}}</h2>

component.ts组件.ts

    iSpeed: any;
    
    //BUTTONCLICK
    speedTest(){
        //WORKS
        this.iSpeed = "LOADING";
        socket.emit("checkedTrue");
    }
    ngOnInit(): void {
        socket.on('acknowledged', (data: any) =>{
            //LABEL CHANGE
            this.iSpeed = data.internetSpeed;
            alert(this.intSpeed = data.internetSpeed);
        })
    }

Angular Newbie, where I am being dumb? Angular 新手,我哪里傻了?

Looks like problem with change detection.看起来像是变更检测的问题。 You can try this你可以试试这个

constructor(private cdr: ChangeDetectorRef) {}

ngOnInit(): void {
    socket.on('acknowledged', (data: any) =>{
        //LABEL CHANGE
        this.iSpeed = data.internetSpeed;
        
        this.cdr.detectChanges();
        alert(this.intSpeed = data.internetSpeed);
    })
}

If you are using onPush change detection strategy, first case works because change detection is called after click, but second one doesn't如果您使用 onPush 更改检测策略,则第一种情况有效,因为单击后会调用更改检测,但第二种情况不会

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

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