2017-02-21 61 views
1

這裏選擇特定的記錄是我的角色類如何從可觀察的angular2

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

+0

如果那是http,那麼我猜你需要訂閱。 – Jai

+0

你的組件是什麼樣子的,你可以發佈它嗎? –

回答

3

你觀察到的roles是一個數組中的單個項目,它不是可觀察到該數組內的項目,所以role.id當你試圖過濾不存在​​您需要遍歷這個數組才能夠提取值:

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

有了這個,你結了一個可觀察的selected這將作爲一個數組。如果你想要一件物品或幾件物品,可能會有點不確定......但是如果你只需要一件物品,那就用find來代替,那麼你最終不會得到一個像樣的可觀察物體,而是一個像可觀察的物體。

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

希望這有助於! :)

至於有點不清楚,就好像你想要使用observables或不使用。如果你不想使用observables,只需訂閱你自己,然後過濾這些值:

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) 
    }) 
+0

現在如何凸輪我打印編號從selectedRole控制檯 –

+0

現在打印來自selectedRole值是可觀察類型的值,我必須訂閱selectedRole!對 ? –

+1

如果您在我的答案中使用了後一種解決方案,您可以通過'{{(selectedRole | async)?. id}}打印id。'如果您不想使用observables,則需要稍微更改代碼。但我認爲你想用observables :) – Alex