通过.subscribe()将对象数组分配给变量

时间:2017-11-04 19:48:59

标签: angular routes observable subscribe

我关注Angular.io指南https://angular.io/guide/router#route-parameters-in-the-activatedroute-service。他们使用的| 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); }

<小时/> 的 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' }
];

1 个答案:

答案 0 :(得分:1)

你打错了。您的this.heroes == heroes必须是this.heroes = heroes

相关问题