Angular2 - 如何观察数组?

时间:2017-03-11 00:37:50

标签: angular angular2-observables

这就是我所拥有的:

// settings.ts

public messages : Array<Message>;

public static getInstance() {
   if (this.instance == null) {
      this.instance = new Settings();
   }
      return this.instance;
}

this.client.onMessageArrived = (message: Message) => {
  this.messages.push(message);     //new message is pushed in to the array
};

// log.component.ts

public msgs: Array<String>;

Settings.getInstance().messages.forEach(element => {
   this.msgs.push(element.getText());  //here I get the messages from settings.ts
});

// log.component.html

<ng-container  *ngFor="let msg of msgs">
   <md-card>{{msg}}</md-card>
</ng-container>

所以我想要的是:每当一个新的Messege到来时,html也应该显示新的消息。

我知道我必须使用Observables,我确实在互联网上寻求帮助,但我仍然不知道如何解决这个问题....

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

以下代码可以帮助您,

 Settings.getInstance()
        .subscribe((messages)= >{
          messages.forEach(element => {
                this.msgs.push(element.getText());  //here I get the messages from settings.ts
                });
        });

该服务应修改为

    public static getInstance() :Obserable<Message[]>) {
        if (this.instance == null) {
            //your http service call and map the response object 
        }
        return this.instance;
    }
.
.
.
this.client.onMessageArrived = (message: Message) => {
            this.messages.push(message);     //new message is pushed in to the array
        };
.
.