我是Angular2的新手,正在尝试让一个自定义组件使用一个管理Mongo.Collection对象注册表的服务。我的问题是,当Collection已经加载时,我似乎不能很好地刷新UI。
如果你看一下下面的代码,你会发现有一个注入了DatasetService的组件。此服务管理集合的注册表。我猜这个问题与Meteor.autorun()方法将处理带出了角度“区域”有关&我需要以某种方式将该进程重新注入到角度区域/摘要中?
客户端和服务器:
export const Meetings = new Mongo.Collection<any>('meetings');仅服务器
Meteor.publish('meetings', function(options: any) {
return Meetings.find({});
});仅限客户端
class Dataset {
cursor: Mongo.Cursor<any>;
loading: boolean = true;
constructor( public collection: Mongo.Collection<any> ) {
Tracker.autorun(() => {
this.loading = true;
Meteor.subscribe('meetings', {}, () => {
this.cursor = this.collection.find({});
this.loading = false;
});
});
}
}
@Injectable()
class DatasetService {
datasets: Dataset[] = [];
register( id: string, collection: Mongo.Collection<any> ) : Dataset {
return this.datasets[id] = new Dataset( collection, options );
}
}
@Component({
selector: 'meetings-list',
template: `<ul><li *ngFor="let meeting of meetings.cursor">{{meeting.name}}</li></ul>`,
viewProviders: [DatasetService]
})
class MeetingsListComponent extends MeteorComponent implements OnInit {
meetings: Dataset;
constructor(private datasetService: DatasetService) {
super();
}
ngOnInit() {
this.meetings = this.datasetService.register( 'meetings', Meetings );
}
checkState() {
console.log(this.loading);
}
}如果我加载该页面,则不会显示会议列表。但是,如果我通过单击按钮手动调用'checkState()‘,它就会刷新UI并呈现会议。
任何帮助,清晰或替代的方式来实现我正在尝试做的事情,我将非常感激!
发布于 2016-09-07 05:24:45
你是对的。触发更改的代码来自Angular2专区之外,因此您需要将其推送到专区中以执行更改。为此,您需要将NgZone注入到服务中。然后,您可能需要将其传递给Dataset实例,因为这是应该触发更新的代码所在的位置。例如,这可能会起作用:
import { Injectable, NgZone, Inject } from '@angular/core';
class Dataset {
cursor: Mongo.Cursor<any>;
loading: boolean = true;
constructor( public collection: Mongo.Collection<any>, zone: NgZone ) {
Tracker.autorun(() => {
this.loading = true;
Meteor.subscribe('meetings', {}, () => {
zone.run(() => { //<-- new line
this.cursor = this.collection.find({});
this.loading = false;
}); //<-- end of new line
});
});
}
}
@Injectable()
class DatasetService {
datasets: Dataset[] = [];
private zone: NgZone;
// Inject Here
constructor(@Inject(NgZone)zone: NgZone) { this.zone = zone; }
register( id: string, collection: Mongo.Collection<any> ) : Dataset {
//Add zone to Dataset constructor,
// not sure before or after options (not sure where options comes from or goes
return this.datasets[id] = new Dataset( collection, this.zone, options );
}
}https://stackoverflow.com/questions/39354707
复制相似问题