【问题标题】:Angular2 computed filtered listAngular2计算过滤列表
【发布时间】:2017-12-14 03:56:41
【问题描述】:

我有一个包含社交关系的数组,用于连接客户。我的应用中有 3 个不同的部分,其中显示了邀请连接、现有连接和非邀请/非注册连接。

我正在尝试使用计算属性让我的生活更轻松。

组件段

export class SocialComponent implements OnInit {
    public loaded = false;
    public connections:Connection[] = [];

    constructor(public socialService:SocialService) {
    }

    loadConnections() {
        var self = this;
        return new Promise(function (resolve, reject) {
            self.socialService
                .connections()
                .subscribe(connections => {
                    self.connections = connections;
                    resolve(connections);
                }, error => reject(error));
        });
    }

    public get registeredConnections():Connection[] {
        return this.connections.filter(connection => {
            return connection.exists;
        });
    }

    ngOnInit() {
        var promises = [];

        promises.push(this.loadConnections());
        //..... 
        //other promises here
        //.....

        Promise.all(promises).then(values => this.loaded = true);
    }
}

模板

<div class="well">
    <h4>People you know that are coming</h4>
    {{ registeredConnections | json }}
    <div class="col-md-3" *ngFor="#connection of registeredConnections">
        <connection [connection]="connection"></connection>
    </div>
</div>

当我单独使用{{ registeredConnections | json }} 时,一切正常。

我第二次尝试 ngFor,ngIf 我得到以下错误

EXCEPTION: Expression 'registeredConnections in SocialComponent@5:34' has changed after it was checked. Previous value: ''. Current value: '' in [registeredConnections in SocialComponent@5:34]

【问题讨论】:

标签: angular


【解决方案1】:

显然,在开发模式下,angular 会检查你的绑定两次以确保它们没有改变。

https://github.com/angular/angular/issues/6006

尝试将已注册连接从自动计算的属性更改为常规属性。然后调用一个函数来填充数组:

export class SocialComponent implements OnInit {
    public loaded = false;
    public connections:Connection[] = [];
    public registeredConnections: Connection[];
    loadConnections() {
        var self = this;
        return new Promise(function (resolve, reject) {
            self.socialService
                .connections()
                .subscribe(connections => {
                    self.connections = connections;
                    self.registeredConnections = connections.filter(connection => { return connection.exists; });

                    resolve(connections);
                }, error => reject(error));
        });
    }

【讨论】:

  • 是的,工作正常,但让我的业务逻辑一团糟。无论如何都启用生产模式和这项工作!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2022-09-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-01-18
  • 2018-10-22
  • 2019-12-19
相关资源
最近更新 更多