【问题标题】:Process data depending on multiples observables根据多个可观察对象处理数据
【发布时间】:2017-07-27 17:24:38
【问题描述】:

我有两个来自两个不同 HTTP 调用的 observables。 在我的组件中,我需要调用这两个服务,处理从这些服务返回的数据,并将作为处理结果的另外两个变量发送到模板。

我已经尝试了很多我不能把它们都放在这里的东西,但这里是我迄今为止尝试过的主要解决方案:

  • 在 2 个服务上使用 forkJoin,然后处理数据:执行该处理的函数表示结果未定义。
  • 使用 switchMap :结果与上述相同。
  • 使用 BehaviorSubject : 同样的结果

我不知道我是否忘记了 Observable 或 RxJs 的一些基本规则,但我真的找不到正确的方法。

这是我当前组件中的代码:

  public notifGroups: any;
  public currentUser: any;
  public currentUserGroups: any;
  public notifGroupsImOut: any;

  private _notifGroupsImIn: BehaviorSubject<any> = new BehaviorSubject([]);

  public readonly notifGroupsImIn: any = this._notifGroupsImIn.asObservable();

  constructor(
    private _groupService: GroupService,
    private _currentUserService: CurrentUserService,
    private _userService: UserService,
  ) { }



  ngOnInit() {
     this.test().subscribe(
     res => {
      console.log(res);
      for(let mGroup in res[1]["user"]["subscriptionsToGroups"]){
        for(let nGroup in res[0]["list"]) {
          console.log(nGroup);
          console.log(mGroup);
          if (mGroup["group"]["email"] == nGroup["email"]){             
             this._notifGroupsImIn
                .next(this._notifGroupsImIn.getValue().push(nGroup));
          }
        }
      }
      this.notifGroupsImIn.subscribe()
    }
  )
}



  private _getNotifGroups(): any{
    return this._groupService
      .getGroupsByType('NOTIFICATION')
  }

  private _getCurrentUser() {
    return this._currentUserService
      .getCurrentUser()  
  }

  public getAll(){
    return Observable.forkJoin(this._getNotifGroups(), this._getCurrentUser())
  }

  public test(): Observable<Array<any>> {
     let obs = this.getAll();

     obs.subscribe(
         res => {
            console.log(res);
            this.notifGroups = res[0]["list"];
            this.currentUser = res[1]["user"]["subscriptionsToGroups"];
       }
    )
    return obs
 }

好吧,我知道现在代码的某些部分很脏,但我希望你不要挖掘太多。

所以我想做的是:

我从两个服务中得到以下值:notifGroups 和 currentUserGroups。

它们都是对象列表。

然后在我的 test() 函数中,我将每个对象与另一个对象进行比较,如果这个对象的 email 属性等于另一个,我将它添加到 notifGroupImIn。

但是在调用 test() 函数时,看起来 http 调用的结果还没有解决,即使我在 ngOnInit 中调用它们并订阅了它们。

我不确定我是否足够理解,所以请告诉我。

谢谢。

更新

我更改了一些代码,因为在模板中,notifGroupsImIn 仍然是可观察的。现在我有以下错误:无法读取未定义的属性“电子邮件”。引发错误的电子邮件属性是这两个属性之一:

if (mGroup["group"]["email"] == nGroup["email"]){                  
  this._notifGroupsImIn.next(this._notifGroupsImIn.getValue().push(nGroup));
}

还有两行

console.log(nGroup);
console.log(mGroup);

在控制台中都返回 0,不知道为什么,res[1]["user"]["subscriptionsToGroups"]res[0]["list"] 正确返回了对象列表

【问题讨论】:

  • 将数组传递给flatMap 将看到单独发出的数组值,但您的 sn-p 似乎期望发出一个数组。这不会发生。
  • “另外两个变量是模板的 proc(c) 的结果。”他们叫什么?很难在前几行中阅读您的问题是什么。您希望实现什么。需要更“有力”/在帖子早期以吸引读者..
  • 确实,我并没有说到重点。实际上,由于我尝试过的所有事情,我的代码变得一团糟。

标签: angular typescript rxjs observable


【解决方案1】:

forkJoin 的简单示例

@Component({
  selector: 't-root',
  template: `
    <div>{{groups}}</div>
    <div>{{user}}</div>
  `
})
export class AppComponent {

  groups: any;
  user: any;

  // Assume this method calls this._groupService.getGroupsByType('NOTIFICATION')
  private _getNotifGroups(): Observable<any> {
    return Observable.of('GROUPS');
  }

  // Assume this method calls this._currentUserService.getCurrentUser()  
  private _getCurrentUser(): Observable<any> {
    return Observable.of('USER');
  }

  private getAll(): Observable<any> {
    return Observable.forkJoin( this._getNotifGroups(), this._getCurrentUser() );
  }

  ngOnInit(): void {
    this.getAll().subscribe(res => {
      console.log(res); // ['GROUPS', 'USER']
      this.groups = res[0];
      this.user = res[1];
    });
  }

}

【讨论】:

  • 感谢您的回答,但这部分已经对我有用,当我尝试在我的组件中处理这些数据时失败了。
【解决方案2】:

你试过combineLatest

combineLatest:只要任一可观察序列产生一个元素,就使用选择器函数将指定的可观察序列合并为一个可观察序列。

public getAll(){
   return Observable.combineLatest(
       this._getNotifGroups(), 
       this._getCurrentUser()
   );
}

combineLatestDocs

如果它不起作用,请说明错误是什么或为什么它不起作用。

【讨论】:

    猜你喜欢
    • 2020-08-10
    • 1970-01-01
    • 2011-06-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多