【发布时间】:2021-11-08 00:14:44
【问题描述】:
我正在创建一个 Observable 来处理我需要参数的数据。对于添加的新值,使用了 BehaviourSubject。
heroes$: Observable<any> = this.heroService.heroes$
constructor(private heroService: HeroService){
this.heroes$.subscribe(x=> console.log('fffffffffff',x)
)
}
//result up is empty
<li *ngFor="let hero of heroes$ | async">
<a routerLink="/detail/{{hero.id}}">
<span class="badge">{{hero.id}}</span> {{hero.contentmsg}}
</a>
<button class="delete" title="delete hero"
(click)="delete(hero)">x</button>
</li>
Than in service 实现了一个简单的逻辑来列出数据并添加新数据。
heroes$ = merge(
this.allHeroes$,
this.heroCUDAction$
.pipe(
tap(data => console.log('333333333', data)), //data here displayed corectly
scan((heroes, heroAction) => this.modifyHeroArray(heroes, heroAction), [] as any[]),
);
private modifyHeroArray(heroes: any[], value: Action<any> | any[]): any[] {
if (!(value instanceof Array)) {
if (value.action === `add`) {
// Add the hero to the array of heroes
return [...heroes, value.hero];
}
} else {
return [...value];
}
return heroes;
}
调用的服务是一个 Post 请求
allHeroes$ = this.getSpecificMessage(
{
"id_conv":1,
"skipData": 0
}
)
getSpecificMessage(req:any): Observable<any> {
return this.http.post<any>(
`http://localhost:3000/conversation/getSpecificMessage`, {
"from_user":1,
"to_user":2
}, httpOptions
)
.pipe(
tap(data => console.log('data', data)),
catchError(this.handleError<any[]>('getHeroes', []))
)
}
【问题讨论】:
标签: angular ionic-framework rxjs observable