【发布时间】: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