模型更改后Angular 2视图未更新

时间:2017-04-11 22:01:50

标签: angular

即使我的模型明确更新,也无法更新我的观点。尝试使用NgZone,但它没有帮助。

我在两个组件中注入RouteService:app.component和start-page-list.component。 RoutService使用Subject在组件之间传递数据:

import { Injectable } from '@angular/core';
import { Round } from "app/round";
import { Subject } from "rxjs/Subject";

@Injectable()
export class RoundService {

  private roundSource = new Subject<Round>();

  roundItem$ = this.roundSource.asObservable();

  changeRound(value:Round) {
    this.roundSource.next(value);
  }
}

app.components视图按预期更新,但start-page-list.component没有。

app.component:

import { Component } from '@angular/core';
import { Http } from "@angular/http";
import 'rxjs/add/operator/toPromise';
import { RoundService } from "app/round.service";
import { Round } from "app/round";

@Component({
  selector: 'app-root',
  template: `
  <div class="container">
  <div class="page-header">
    <h1>{{currentRound.id}}</h1>
  </div>  
  </div>
  <router-outlet></router-outlet>
  `,
  styleUrls: []
})
export class AppComponent {
  currentRound: Round = {id:0,name:"No round set yet"};

  constructor(private http: Http, private round : RoundService) { }

  callBackFunc(data:Round) {
    this.currentRound = data;
  }

  ngOnInit() {
    this.round.roundItem$.subscribe(
      (data:Round) => this.callBackFunc(data)
    );
  }  
}

这里currentRound.id已更新!

start-page-list.component(在app.component中的router-outlet处呈现):

import { Component, OnInit, Input, NgZone } from '@angular/core';
import { PlayerService } from "app/player.service";
import { Game } from "app/game";
import { Player } from "app/player";
import { GameService } from "app/game.service";
import { RoundService } from "app/round.service";
import { Round } from "app/round";
import 'rxjs/add/operator/toPromise';

@Component({
  selector: 'app-start-page-list',
  template: `{{currentGameset.id}}`,
  styleUrls: []
})
export class StartPageListComponent implements OnInit {

  currentGameset:Round = {id:0,name:'No round set yet'};

  constructor(private gameService: GameService, private roundService: RoundService, private zone: NgZone) { }

  callbackFunc(data:Round) {
    this.currentGameset = data;
    console.log("currentGameset.id= " + this.currentGameset.id);
  }

  ngOnInit() {
    this.roundService.roundItem$.subscribe(
      (data:Round) => this.zone.run( () => this.callbackFunc(data) )
    );
  }  

}

这里即使模型是(控制台日志显示更新的值),currentGameset.id也不会更新。如您所见,我尝试过使用NgZone。

有什么建议可能会出错?

修改 如果我将start-page-list.component作为子组件放到app.component我不会遇到问题。然后视图按照我的预期更新。问题似乎只有在我使用组件的路由器出口渲染时才会出现。

2 个答案:

答案 0 :(得分:0)

执行currentGameset = data时,您将破坏模板所指的内容。你会认为它会继续引用currentGameset,但这不是它的工作方式!

尝试为currentGameset添加一个包装器,如:

gameSetParent = { 
  currentGameset: {id:0,name:'No round set yet'};
}

在回调函数中,

this.gameSetParent.currentGameset = data;

您需要更新模板以反映更改。

答案 1 :(得分:0)

原来在服务中使用BehaviorSubject而不是Subject是解决方案!

有人在乎解释原因吗?