Angular2 View Not Changing After Data Is Updated

前端 未结 6 1422
长情又很酷
长情又很酷 2020-12-09 15:42

I am trying to update my view after a websocket event returns updated data.

I injected a service into my app and call getData() method on the service. This method em

6条回答
  •  悲&欢浪女
    2020-12-09 16:21

    So I finally found a solution that I like. Following the answer in this post How to update view after change in angular2 after google event listener fired I updated myList within zone.run() and now my data is updated in my view like expected.

    MyService.ts

    /// 
    
    // Import
    import {NgZone} from 'angular2/angular2';
    import {SocketService} from 'js/services/SocketService';
    
    export class MyService {
        zone:NgZone;
        myList:Array = [];
        socketSvc:SocketService;
    
        constructor() {
            this.zone = new NgZone({enableLongStackTrace: false});
            this.socketSvc = new SocketService();
            this.initListeners();
        }
    
        getData() {
            this.socketSvc.emit('event');
        }
    
        initListeners() {
            this.socketSvc.socket.on('success', (data) => {
                this.zone.run(() => {
                    this.myList = data;
                    console.log('Updated List: ', this.myList);
                });
            });
        }
     }
    

提交回复
热议问题