在过去几年与AngularJS合作之后,我刚刚开始使用Angular 2。
我有一个组件,它显示有关用户的一些信息,并根据声明的变量,标记将根据showStuff
变量的值进行调整。 stuff2
是默认值。 stuff1
应显示重复的数据列表。当用户单击showStuffOne()
时,变量确实更改为正确的值,但是函数中订阅的数据未更新到视图。
当在此特定实例中模型更改时,我对正确的“angular2”方式感到有点难以更新视图。我看过很多关于DetectionChange,ngZone和behaviorSubject的帖子,但不确定哪个方向会解决这个问题。请考虑以下事项:
用户-page.html中
<ion-row>
<ion-col>
<button ion-button block (click)="showStuffOne()"> Stuff1 </button>
</ion-col>
<ion-col>
<button ion-button block> Store </button>
</ion-col>
<ion-col>
<button ion-button block (click)="showStuffTwo()"> Stuff2 </button>
</ion-col>
</ion-row>
<ion-list *ngIf="showStuff == 'stuff1'" ngFor="let event of eventList" >
<h3>{{event.title}}</h3>
<span>{{event.location}}</span>
</ion-list>
<ion-list *ngIf="showStuff == 'stuff2'">stuff2</ion-list>
用户-page.ts:
import { Component, NgZone, OnInit, ChangeDetectorRef } from '@angular/core';
import { NavController, NavParams, ModalController } from 'ionic-angular';
import { AngularFireDatabase, FirebaseObjectObservable, FirebaseListObservable} from 'angularfire2/database';
import * as firebase from 'firebase/app';
@Component({
templateUrl: 'user-page.html',
selector: 'user-page'
})
export class UserPage {
userId: string;
eventList: string[];
showStuff: string;
constructor(private cd: ChangeDetectorRef, private zone: NgZone, public navCtrl: NavController, public navParams: NavParams, private afDB: AngularFireDatabase, public modalCtrl: ModalController) {
console.log(this.navParams.get('username'))
var getUsr = afDB.list('https://myendpoint.com/users', {
query: {
orderByChild: 'uname',
equalTo: this.navParams.get('username')
}
}).subscribe(data => {
console.log(data)
this.userId = data[0].uid;
})
}
ngOnInit() {
this.showStuff = 'stuff2';
}
showStuffOne() {
console.log("stuff1")
this.userEvents(this.userId);
}
showStuffTwo() {
console.log("stuff2")
this.showStuff = 'stuff2';
}
openEvent = function(key) {
console.log(key)
let eventObj = {
eventKey: key
}
let eventModal = this.modalCtrl.create(EventModal, eventObj);
eventModal.present()
};
userEvents(userid: string) {
var getUsrEvnts = this.afDB.list("http://myendpoint.com/event", {
query: {
orderByChild: "created_by",
equalTo: userid
}
}).subscribe(data => {
this.showStuff = 'stuff1'; // this correctly updates the variable, changing the view
this.eventList = data; // data not updating, returning undefined, however the data logs here
console.log(this.eventList)
})
}
}
修改 答案可以在 this posting