Observable 在 Api 调用时订阅空结果

Observable subscribe empty result on Api call

我正在创建一个 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>

比在服务中实现了一个简单的逻辑来列出数据和添加新数据。

  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', []))
      )
  }

已解决。

已经是一个糟糕的结果

scan((heroes, heroAction) => this.modifyHeroArray(heroes, heroAction), [] as any[]),

我评论后得到了准确的结果

注意您如何转换数据。

添加管道和其他功能没问题。 如果水龙头工作正常,订阅也应该工作。 所以错误最终会在扫描时出现。

.管道( tap(data => console.log('333333333', data)), //这里的数据正确显示 scan((heroes, heroAction) => this.modifyHeroArray(heroes, heroAction), [] as any[]),
);