2016-10-06 46 views
0

我正在開發Ionic2/rc0上的應用程序。我在單頓服務上獲得了一個ReplaySubject,可以使當前用戶在整個應用程序中保持一致。這一切工作正常,我可以訂閱,並得到用戶對象一樣容易MongoDB的Rxjs工作流程文檔參考

this._user.Current.subscribe(user=>{ console.log(user)}); 

用戶對象看起來像這樣

User { 
    confirmed:true 
    devices:["57f65werwe343bn8843f7h","7yr3243h5429hf2hjd"] 
    friends:["t245y53h65346htyh","356ytrer75dfhg43we56df"] 
    email:"[email protected]" 
    id:"57f6525e926bbc7615fc5c5c" 
    notification:false    
    password="$2a$04$.Fk/8eMj18ZrkfurbbdP4uT3yOs7Lb9db74GkNfgtABVY.ez2Q0I." 
    picture:"https://api.cescoferraro.xyz/kitty" 
    role:"master" 
    username:"cesco" 
} 

正如你可以看到我的後臺是使用MongoDB的具有單如here所述的與文檔引用的多對多關係。

我創建了一個設備標籤,我想顯示那些用戶設備上的所有數據,但我需要調用this._devices.info爲current.devices的每一個和Concat的結果回TrueDevices

@Component({ 
    template: ` 
      <ion-header> 
       <ion-navbar> 
        <ion-title>Tabs</ion-title> 
       </ion-navbar> 
      </ion-header> 
      <ion-content> 
       <h2>Device:list</h2> 

       <h2 *ngFor="let item of devices | async">{{item}}</h2> 

       <button ion-button (click)="readDevice()">Read Random Device</button> 
      </ion-content> 
` 
}) 
export class DeviceComponent { 
    devices: Observable<string[]>; 
    TrueDevices: Observable<Device[]>; 

    constructor(public _user: UserService, public _device: DeviceService) { 

     this._user.Current.subscribe(user=>{ this.devices = Observable.of(user.devices)}); 

     // Get current User 
     // call this._devices.info for each one of current.devices 
     // concat the result back to TrueDevices 
     this._user.Current 
      .subscribe((result) => { console.log(result) }); 

    } 

    readDevice(){ 
     console.log(this.devices); 
     this._device.info(this.devices.value[0]).subscribe(data=>console.log(data)) 
    } 
} 

我需要重複相同的程序到朋友選項卡等。我非常肯定有幾個操作員會做這個魔術,但我對rxjs還是比較陌生的,並且不熟悉它們。什麼是正確的方法?

回答

1

this._user.Current 
 
    .switchMap(user => Observable.from(user.devices)) // after this line, you have an Observable<string> 
 
    .mergeMap(device => this._device.info(device)) // each device will be mapped to another observable(or stream), and all the streams will be merged together 
 
    .toArray() // wait for all the streams to complete and reduce all the results into an array. 
 
    .subscribe(array => console.log(array));

或去小膠質房間: https://gitter.im/Reactive-Extensions/RxJS