【问题标题】:Angular 4 update array from service and in the view来自服务和视图的 Angular 4 更新数组
【发布时间】:2017-12-15 11:27:41
【问题描述】:

我有一项从 API 获取数据的服务。我有一个使用这项服务的组件。

一旦数据到来,它将消息数组存储在 messages[] 变量中。然后在视图中我执行 ngFor 循环来循环对象并显示数据。一切正常,但我有另一个函数,当用户单击按钮时触发,该函数使用相同的服务但​​传递不同的参数,因此返回不同的结果,因此它应该更新 messages[] 变量并更新视图。

但是应用程序崩溃的问题,我不知道为什么,它没有更新消息[]。那么如何在函数调用时更新同一个变量并在视图中显示变化呢?

这是我的服务:

//returns all messages from API passing pagenumber and how many results to return
getAllMessages(page: number, numberOfRows: number): Observable<any> {
    return this.http.get('/api/messages?offset=' + page + '&batchsize=' + numberOfRows).map(data => data)
}

所以在我的组件中:

   messages: any[];

    ngOnInit() {

       setDefaultPageLoad(pageOffset: number) {
    this.messageService.getAllMessages(pageOffset, 25).subscribe(data => {
       this.messages = data.messages,

    }

         }
      otherFunction(){
          this.messageService.getAllMessages(pageOffset, 12).subscribe(data => {
       this.messages = data.messages,

       }

    })

还有风景

<button (click)="otherFunction()">Update<button> //Once clicked should update
   <div *ngFor="let message of messages">
     {{message.name}}
   </div>

【问题讨论】:

  • 功能有问题
  • 问题是什么?你没有提供任何错误...
  • chrome 只是冻结它似乎在循环

标签: angular service observable


【解决方案1】:

您在 ngFor

中缺少 "
 <div *ngFor="let message of messages">
     {{message.name}}
   </div>

函数也应该有括号()

(click)="otherFunction()"

【讨论】:

  • (click)="otherFunction()" 应该是
猜你喜欢
  • 2018-04-07
  • 2017-11-28
  • 1970-01-01
  • 1970-01-01
  • 2018-01-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多