【问题标题】:How to add New Item onto Observable of type Array?如何将新项目添加到 Array 类型的 Observable 上?
【发布时间】:2021-01-15 18:26:20
【问题描述】:

我正在研究英雄的角度之旅示例。有一项功能可以将新英雄添加到现有英雄列表中。 我在 hero.service.ts 中添加英雄的方法如下:

addNewHero(hero : Hero) : Observable<Hero> {
    console.log(hero)
   return this._http.post<Hero>(this.url,hero).pipe(
    tap(res => this._service.addMessage(`new hero is ${hero.name} added`)),
    catchError(error => this.handleerror('adding a hero'))

   )
  }

Heroescomponent 类中的 addHero 方法如下:

export class HeroesComponent implements OnInit {

  heroes : Observable<Array<Hero>>;
  selectedHero: Hero;

  constructor(private _service : HeroService,private _router : Router) { }

  ngOnInit() {
    this.heroes = this._service.getHeroes()
  }

  onSelect(hero: Hero): void {
    this.selectedHero = hero;
  }

  details(id : Number) {
    this._router.navigate(['heroes',id])
  }

  **addHero(name : String){
    console.log(name)
    this._service.addNewHero({ name } as Hero).subscribe((res : Hero) => {
      this.heroes = this._service.getHeroes()
     
    })
  }**
}

Heroes.HTML 文件如下:

<h2>My Heroes</h2>
<div>
  <input type="text" #heroname>
  <button (click) = "addHero(heroname.value)">Add</button>
</div>
<ul class="heroes">
  <li *ngFor="let hero of heroes | async">
    <a routerLink = "/detail/{{hero.id}}"
    style = "text-decoration : none"><span class="badge">{{hero.id}}</span> {{hero.name}}</a> 
  </li>
</ul>

我正在使用heroes 类型为Observable&lt;Hero[]&gt; 的变量。

所以,每当我添加一个新英雄时,我都想在现有的heroes 中添加一个新添加的英雄。但是,我无法做到这一点,因为observable of arrays 没有推送方法。所以,我再次调用getHeroes 方法来刷新列表以显示新添加的项目。是否有任何解决方法将项目添加到数据类型Observable&lt;Array&gt; 而不是再次访问服务器

【问题讨论】:

    标签: arrays angular rxjs-observables


    【解决方案1】:

    您可以使用Subject,如下所示:

    export class HeroesComponent implements OnInit {
    
        heroes = new Subject<Array<Hero>>();
        heroes$ = this.heroes.asObservable();
        selectedHero: Hero;
      
        constructor(private _service : HeroService,private _router : Router) { }
      
        ngOnInit() {
          this._service.getHeroes().subscribe(heroes => this.heroes.next(heroes))
        }
      
        onSelect(hero: Hero): void {
          this.selectedHero = hero;
        }
      
        details(id : Number) {
          this._router.navigate(['heroes',id])
        }
      
        addHero(name : String){
          
          this._service.addNewHero({ name } as Hero).pipe(
              withLatestFrom(this.heroes)
          ).subscribe(([newHero, currentHeroes]) => {
            this.heroes.next(currentHeroes.concat(newHero))
           
          })
        }
      }
    

    Subject 提供了next 方法,它允许您发出一个新值,然后该值将成为heroes$ Observable 的值,因为heroes Subject 是它的源。

    【讨论】:

      猜你喜欢
      • 2013-11-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-05-06
      • 2017-02-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多