【问题标题】:Rxjs workflow for MongoDB Document ReferencesMongoDB 文档参考的 Rxjs 工作流程
【发布时间】:2016-10-06 16:25:54
【问题描述】:

我正在 Ionic2/rc0 上开发一个应用程序。我在单例服务上获得了一个 ReplaySubject,它使当前用户在整个应用程序中保持一致。一切正常,我可以订阅它并获得一个 User 对象,就像

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

User 对象如下所示

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

如您所见,我的后端正在使用具有一对多关系和文档引用的 MongoDB,如 here 所述。

我创建了一个设备选项卡,我想在其中显示有关这些用户设备的所有数据,但我需要为每个 current.devices 调用 this._devices.info 并将结果连接回 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 还很陌生,并不熟悉所有这些操作员。什么是正确的方法?

【问题讨论】:

    标签: mongodb angular ionic2 rxjs5


    【解决方案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));

    或者去 gitter 房间: https://gitter.im/Reactive-Extensions/RxJS

    【讨论】:

      猜你喜欢
      • 2019-08-04
      • 2021-01-17
      • 1970-01-01
      • 2015-07-06
      • 2016-05-11
      • 1970-01-01
      • 1970-01-01
      • 2022-08-10
      • 1970-01-01
      相关资源
      最近更新 更多