即使我的模型明確更新,也無法讓我的視圖更新。嘗試使用NgZone,但它沒有幫助。模型更改后角度2視圖不更新
我在兩個組件中注入RouteService:app.component和start-page-list.component。 RoutService使用除組件之間傳遞數據:如預期,但啓動頁面list.component不
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視圖獲取更新。
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更新!
啓動頁list.component(在app.component在路由器出口呈現):
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。
有什麼建議可能是錯誤的嗎?
編輯 如果我把啓動頁面list.component作爲子組件到app.component我沒有得到問題。然後視圖得到更新,如我所料。這個問題似乎只在我使用組件的router-outlet渲染時纔會出現。
你在哪裏叫'changeRound'? – echonax
另一個由router-outlet渲染的組件。 – John