【问题标题】:Using pipe in *ngFor, the page sometimes updates, sometimes not在 *ngFor 中使用管道,页面有时会更新,有时不会
【发布时间】:2016-05-25 19:19:34
【问题描述】:

我正在使用 angular2-meteor,我已经在使用 pure: false。但是管道有时会运行,有时不会。有关问题的详细信息,请参阅代码中的我的 cmets。

谢谢

<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;
    }
}

【问题讨论】:

  • 什么是 usersCursor.fetch?是异步调用吗?
  • @pixelbits 很抱歉不清楚,只是更新。它基本上从数据库中获取所有用户

标签: meteor typescript angular angular2-meteor


【解决方案1】:

更新:错误似乎是fixed

我认为问题与 angular2-meteor 有关。

当您尝试从 Mongo 获取数据时,我终于找到了一种使用 sort 的工作方式。所以不再使用排序管道了。

但是users:Mongo.Cursor&lt;Meteor.User&gt;不能和*ngFor一起使用,需要先fetch()再使用Array&lt;Meteor.User&gt;,否则列表顺序改变时会报这个错误:

无法读取未定义的属性“状态”

但是列表不会在 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);
}

【讨论】:

    【解决方案2】:

    我不知道调用Meteor.users.find()usersCursor.fetch() 背后的确切原因,但我认为您的用户的检索应该在过滤器本身之外完成。我猜有一部分是在过滤器中完成的(使用usersCursor.fetch()?),这可能是问题所在......

    【讨论】:

    • 谢谢,但是如果我改成this.users = Meteor.users.find().fetch();,情况会变得更糟,我需要手动刷新页面才能看到新的状态,即使没有 orderByStatus 管道。
    • fetch / find 方法返回什么?可观察的?数据?
    • find 将返回Mongo.Cursor&lt;Meteor.User&gt;,fetch 将返回Array&lt;Meteor.User&gt;。他们都可以直接使用*ngFor
    • 或许这个问题对你有帮助:stackoverflow.com/questions/34456430/…
    • 我做了一个测试并稍微改变了我的代码。所以现在这一切都是因为只有一个函数 users.sort()。没有它,页面可以自动更新;有了它,页面有时会自动更新,有时不会。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-07
    • 1970-01-01
    • 1970-01-01
    • 2014-08-04
    • 1970-01-01
    • 2020-01-02
    相关资源
    最近更新 更多