【问题标题】:Add item inside BehaviorSubject在 BehaviorSubject 中添加项目
【发布时间】:2021-07-09 09:30:00
【问题描述】:

我需要在 BehaviorSubject 中添加项目。

我需要在每个对象中添加带有名称的项目(项目名称已扩展) 我尝试了什么:

【问题讨论】:

  • 我不清楚:response 的类型和dates 的类型是什么?
  • 我会尽力解释更好的等待分钟

标签: angular typescript rxjs behaviorsubject


【解决方案1】:

如果您想为数组中的每个对象添加“扩展”属性,请执行以下操作:

private datesSource: BehaviorSubject<any> = new BehaviorSubject<any>(this.test);
public datesObservable$: Observable<any> = this.datesSource.asObservable();

this.datesSource.next(response); // Set your dates object and subscribe to the observale

this.datesObservable$.subscribe(datesObsdata => {
  datesObsdata.forEach(eachObj => {
    if (eachObj && !eachObj['expanded']) {
      eachObj['expanded'] = false;
    }
  })
})

【讨论】:

    【解决方案2】:

    这是我在服务中通常的做法:

    private refresh$ = new BehaviorSubject(null);
    
    read$(): Observable<Order[]>{
        return this.refresh$.pipe(switchMap(()=>
                this.http.get<Order[]>(`${this._url}/orders`)));
      }
    

    【讨论】:

      【解决方案3】:

      据我了解,您想在 BehaviorSubject 的值数组中添加 expanded 属性。

      这就是你的做法,BehaviorSubject 有 value 属性,其中包含最后发出的数据。

      this.dates.value.forEach(val => (val.expanded = true));
      console.log(this.dates.value);
      

      注意:先修改数据,然后发出下一个值(如@Bojan Kogoj 所示),否则现有订阅者将无法获得最新修改的数据。

      【讨论】:

        【解决方案4】:

        这样的?

        this.someService.getList()
          .subscribe(dates => {
            const fixedDates = dates.map(el => ({...el, expanded: false}));
            this.dates.next(fixedDates)
        });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-06-12
          • 2013-11-04
          • 2013-01-09
          • 2020-12-06
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多