【问题标题】:Angular – edit/remove element in a Subject ArrayAngular – 编辑/删除主题数组中的元素
【发布时间】:2021-12-08 15:35:05
【问题描述】:

我有一个用户数组的主题

  private _currentHeroes = new Subject<Hero[]>();
  currentHeroes = this._currentHeroes.asObservable();
  • 我的目标是只编辑数组的 1 个元素而不订阅

在我的服务中启动用户的功能

powerUp(id: number) {
return this.http
  .post<Hero>(environment.apiUrl + 'heroes/powerUp/' + id, {})
  .pipe(
    tap((updatedHero: Hero) => {
      this._currentHeroes.next(
        // I would like to edit the specific element in the array and than sort them by the power.
      );
    })
  );
  }

删除我的服务中的用户功能

  delete(id: number) {
return this.http.delete<Hero>(environment.apiUrl + 'heroes/' + id).pipe(
  tap((deletedHero) => {
    this._currentHeroes.next(
      // Here I delete the specific element from the array
    );
  })
);
  }

如果主题是 BehaviorSubject,我会这样做:

    powerUp(id: number) {
    return this.http
      .post<Hero>(environment.apiUrl + 'heroes/powerUp/' + id, {})
      .pipe(
        tap((updatedHero: Hero) => {
          this._currentHeroes.next(
            this._currentHeroes.value
              .map((hero: Hero) =>
                hero.id === updatedHero.id ? updatedHero : hero
              )
              .sort((a, b) => a.currentPower - b.currentPower)
          );
        })
      );
  }

  delete(id: number) {
    return this.http.delete<Hero>(environment.apiUrl + 'heroes/' + id).pipe(
      tap((deletedHero) => {
        this._currentHeroes.next(
          this._currentHeroes.value.filter(
            (hero: Hero) => hero.id !== deletedHero.id
          )
        );
      })
    );
  }

但我的目标是在使用 Subject 而不是 BehaviorSubject 时达到同样的效果。

我尝试获取主题的值,但由于它是主题,所以不可能。我尝试在线搜索,但不幸的是,我没有找到任何有用的解决方案来满足我的需求。

有人遇到过这个问题吗?或者如何解决?

【问题讨论】:

    标签: angular subject subject-observer


    【解决方案1】:

    我假设你正在处理一个服务,那么你可以在服务属性中引用你需要修改的数组。

    heroes = [];
    

    然后,在每次操作之后,您可以修改该值,然后使用 Subject 或 Behavior Subject 或您想使用的任何内容发出。

    powerUp(id: number) {
    return this.http
      .post<Hero>(environment.apiUrl + 'heroes/powerUp/' + id, {})
      .pipe(
        tap((updatedHero: Hero) => {
            //modify data reference, to add, update or delete value
            // in this case modify with powerup
            this.heroes = this.heroes
                  .map((hero: Hero) =>
                    hero.id === updatedHero.id ? updatedHero : hero
                  )
                  .sort((a, b) => a.currentPower - b.currentPower)
          // emit the resuelt after every operation 
          this._currentHeroes.next(
            this.herores
          );
        })
      );
      }
    

    请记住,您必须订阅每个返回可观察对象的操作,就像您在代码中显示的那样。

    // for example to hero with id 2
    this.yourHeroService.powerUp(2).subscribe()
    

    【讨论】:

      猜你喜欢
      • 2023-03-09
      • 1970-01-01
      • 2020-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多