【问题标题】:Observable subscribe empty result on Api call可观察的订阅 Api 调用的空结果
【发布时间】: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


    【解决方案1】:

    解决了。

    已经是一个糟糕的结果

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

    经过我的评论能够得到确切的结果。

    【讨论】:

      【解决方案2】:

      小心你如何转换你的数据。

      添加管道和其他功能没关系。 如果点击工作也订阅应该工作。 所以错误最终会在扫描时出现。

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

      【讨论】:

        猜你喜欢
        • 2017-06-21
        • 2017-10-06
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-19
        • 2018-11-16
        • 2019-07-10
        • 2018-07-21
        相关资源
        最近更新 更多