我正在使用angular2-meteor,已经使用了pure: false
。但是管道有时会运行,有时则不会。有关该问题的详细信息,请参见代码中的注释。
谢谢
<div *ngFor="#user of (users|orderByStatus)">
{{user.status.online}}
</div>
users:Mongo.Cursor<Meteor.User>;
ngOnInit()
{
this.subscribe('users', () => {
this.autorun(() => {
this.users = Meteor.users.find();
});
}, true);
}
import {Pipe} from 'angular2/core';
@Pipe({
name: 'orderByStatus',
pure: false
})
export class OrderByStatusPipe {
transform(usersCursor:Mongo.Cursor<Meteor.User>):Array<Meteor.User> {
console.log("OrderByStatusPipe runs");
// (1) If I only do these two lines, the change of other users' status can show on the screen immediately.
// let users = usersCursor.fetch();
// return users;
// (2) If sort users by status, the page sometimes updates, sometimes not when user status change.
// If not update automatically, I click that part of screen, it will update then.
let users:Array<Meteor.User> = usersCursor.fetch();
users.sort((a, b) => {
return (a.status.online === b.status.online) ? 0 : (a.status.online ? -1 : 1);
});
return users;
}
}
更新:该错误似乎已修复。
我认为问题与angular2-meteor有关。
最后sort
,当您尝试从Mongo获取数据时,我找到了一种使用的工作方式。因此,不再使用排序管道。
但是您不能users:Mongo.Cursor<Meteor.User>
与* ngFor一起使用,需要fetch()
先使用和Array<Meteor.User>
,否则当列表顺序更改时,它将显示此错误:
无法读取未定义的属性“状态”
但是,该列表不会在UI中自动更新。所以你需要使用NgZone
。
所以最终的工作代码是这样的:
<div *ngFor="#user of users)">
{{user.status.online}}
</div>
users:Array<Meteor.User>; // here cannot use users:Mongo.Cursor<Meteor.User>
constructor(private _ngZone:NgZone) {}
ngOnInit()
{
this.subscribe('users', () => {
this.autorun(() => {
this._ngZone.run(() => {
this.users = Meteor.users.find().fetch();
});
});
}, true);
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句