【发布时间】:2020-11-15 12:36:41
【问题描述】:
如何调用在循环(管道 -> 映射)中返回可观察对象(主题)的函数?函数的参数每次都不一样。
我试着用一个例子来解释:
export class MyClass implements OnInit {
private keyFigureSubject = new Subject();
keyFigures$ = this.keyFigureSubject.asObservable();
load() {
const clients$ = of([{ id: 1, name: 'Mustermann' }, { id: 2, name: 'Hans Dampf' }, { id: 3, name: 'Pleite AG' }]);
const result = clients$.pipe(
flatMap((clients)=> clients),
map(client => this.loadKeyfigures(client.id)) // this isnt working
);
result.subscribe(x=>console.log(x));
}
loadKeyfigures(clientId: number) {
// EDIT: This is a http call in "real life"
const keyFigures = [];
keyFigures.push({clientId: 1, name: 'A', value: 23});
keyFigures.push({clientId: 1, name: 'B', value: 22});
keyFigures.push({clientId: 2, name: 'A', value: 12});
keyFigures.push({clientId: 3, name: 'A', value: 312});
keyFigures.push({clientId: 3, name: 'B', value: 12333});
keyFigures.push({clientId: 3, name: 'C', value: 4567});
keyFigures.push({clientId: 3, name: 'D', value: 54});
keyFigures.push({clientId: 4, name: 'A', value: 5672});
keyFigures.push({clientId: 5, name: 'A', value: 243});
keyFigures.push({clientId: 6, name: 'A', value: 334});
keyFigures.forEach(keyFigure =>{
if(keyFigure.clientId === clientId){
this.keyFigureSubject.next(keyFigure);
}
});
return this.keyFigureSubject.asObservable();
}
}
最后我想要一个类似的列表:
Client 1; Keyfigure A; 23
Client 1; Keyfigure B, 22
问题似乎是在调用返回subject.asObservable() 之前调用了subject.next()。如果我订阅该属性,我将无法传递参数。
【问题讨论】:
标签: angular typescript rxjs