簡體   English   中英

通過.subscribe()將對象數組分配給變量

[英]Assign array of objects to variable though .subscribe()

我正在遵循Angular.io指南https://angular.io/guide/router#route-parameters-in-the-activatedroute-service 他們使用| async | async對我來說還不清楚,因此我決定進行一些定制化處理。 我想通過.subscribe()將對象數組分配給變量,但無法解決 ((

這是我的代碼的一部分

主要

ngOnInit() {
this.heroes$ = this.route.paramMap.switchMap((params: ParamMap) => {
  this.selectedId = params.get('id');
  return this.heroService.getHeroes();

});
 this.heroes$.subscribe((heroes: Hero[]) => {
   this.heroes == heroes
   console.log(heroes) // Shows array of Objects
   console.log(this.heroes) // Shows undefined
 })


heroService

 getHeroes() { return Observable.of(HEROES); } 


英雄

 import { Hero } from './hero'; export const HEROES: Hero[] = [ { id: 11, name: 'Mr. Nice' }, { id: 12, name: 'Narco' }, { id: 13, name: 'Bombasto' }, { id: 14, name: 'Celeritas' }, { id: 15, name: 'Magneta' }, { id: 16, name: 'RubberMan' }, { id: 17, name: 'Dynama' }, { id: 18, name: 'Dr IQ' }, { id: 19, name: 'Magma' }, { id: 20, name: 'Tornado' } ]; 

你打錯字了。 您的this.heroes == heroes必須是this.heroes = heroes

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM