设置嵌入数组值OnInit()

时间:2018-05-23 14:02:47

标签: angular typescript

我有一个遭遇Heroes []和怪物[]的遭遇对象。我在使用内存web api来获取加载此特定遭遇时的数据:

getEncounter(): void{
const id = +this.route.snapshot.paramMap.get('id');
this.encounterService.getEncounter(id)
  .subscribe(encounter => this.encounter = encounter);
}

这很好用。但是我将不得不调整英雄和怪物属性,所以我想在加载遭遇时将它们加载到单独的数组中:

export class EncounterDetailComponent implements OnInit {
@Input() encounter: Encounter;
heroes: Hero[];
monsters: Monster[];  

constructor(private route: ActivatedRoute, private encounterService: 
EncountersService, private location: Location) { }

ngOnInit() {
this.getEncounter();
this.heroes = this.encounter.heroes;
this.monsters = this.encounter.monsters;
}

但由于某种原因,这不起作用。有人可以向我解释为什么这不起作用以及如何解决它?

修改

类似问题:

add(name: string, player: string, HP: string, AR: string, IM: string, imageUrl: string): void{
name = name.trim();
var hitPoints = +HP;
var armor = +AR;
var initModif = +IM;
if(!name){return;}
this.heroService.addHero({name, player, hitPoints, armor, initModif, imageUrl} as Hero)
 .subscribe(hero =>{ this.heroes.push(hero)});

}

这给了我以下result。但在这里我使用了一个可观察的。

其他信息:

<button (click)="add(heroName.value, heroPlayer.value, heroHitPoints.value, heroArmor.value,heroInitModif.value, heroImageUrl.value)">
Add new hero
</button>


 addHero(hero: Hero): Observable<Hero>{
this.messageService.add(`Heroes Service: added hero w/ name=${hero.name}`);
return this.http.post<Hero>(this.heroesUrl, hero, httpOptions).pipe(
  tap((hero: Hero) => this.log(`added hero w/ name=${hero.name}`)),
  catchError(this.handleError<Hero>('addHero'))
);

}

2 个答案:

答案 0 :(得分:1)

Observable是异步的,您试图在observable从服务器发出数据(遭遇)之前设置值。

试试这个:

getEncounter(): void {
    const id = +this.route.snapshot.paramMap.get('id');
    this.encounterService.getEncounter(id)
       .subscribe(encounter => {
           this.encounter = encounter;
           this.heroes = this.encounter.heroes;
           this.monsters = this.encounter.monsters;
    });
}

ngOnInit() {
   this.getEncounter();
}

答案 1 :(得分:1)

getEncounter()是异步的。你应该返回一个Observable并等待它发出一个值

getEncounter(): Observable<any>{
   const id = +this.route.snapshot.paramMap.get('id');
   return this.encounterService.getEncounter(id)
   .do(encounter => this.encounter = encounter);
}

ngOnInit() {
   this.getEncounter()
   .subscribe( () => {
      this.heroes = this.encounter.heroes;
      this.monsters = this.encounter.monsters;
   })
}