如何从angular2

时间:2017-02-21 12:16:05

标签: angular observable

这是我的角色类

export class Role {
    id: number;
    name: string;

    constructor(id: number, name: string) {
        this.id = id;
        this.name = name;
    }
}

我有roles

roles: Observable<Role[]>;

我正在填写

this.roles = this.roleService.getAllRoles();

现在我想根据id过滤角色。为此,我正在使用

let selectedRole = this.roles.filter(role => role.id === group.role)
                               .map(role=> {console.log(role)});

但这并没有记录任何东西:(。我错过了什么吗?我刚刚开始使用Angular2

1 个答案:

答案 0 :(得分:4)

您的可观察roles是一个数组的单项。它不是该数组中项目的可观察数据,因此当您尝试过滤时,role.id不存在。您需要迭代此数组才能提取值:

let selectedRole = this.roles.map(arr => 
                      { return arr.filter(role => role.id == group.role) })

有了这个,你最终得到一个可观察的selected,它将作为一个数组。如果你想要一个项目或几个项目有点不确定......但是如果你只需要一个项目,那么使用find代替,那么你不会得到一个arraylike observable,而是一个像observable这样的对象。

let selectedRole = this.roles.map(arr => 
                      { return arr.find(role => role.id == group.role) })

希望这有帮助! :)

至于有点不清楚,好像你想要与observables一起工作。如果您不想使用observable,只需订阅自己,然后过滤值:

this.roleService.getAllRoles()
  .subscribe(data => {
     this.roles = data;
     // create an array with roles that match the group role
     this.selectedRole = this.roles.filter(x => x.id == group.role)
     // find a single role that matches the group.role
     this.selectedRole = this.roles.find(x => x.id == group.role)
  })