[英]Angular assign objects in subscribe
I am following a tutorial from here , but I am trying to adapt the heroes.component.ts class slightly by using 'card' instead of 'hero'. 我正在从这里开始学习教程,但是我试图通过使用'card'而不是'hero'来稍微修改heroes.component.ts类。 When I attempt to call
.subscribe()
I am getting 当我尝试调用
.subscribe()
时
ERROR in src/app/card/card.component.ts(12,19): error TS1109: Expression expected.
src / app / card / card.component.ts(12,19)中的错误:错误TS1109:需要表达。
my version (note cardlist variable name change) 我的版本(注意卡片清单变量名称更改)
export class CardComponent implements OnInit {
cardlist = Card[]; //-------LINE 12
....
getCards(): void {
this.cardService.getCards() //--------LINE 19
.subscribe(c => this.cardlist = c);
}
}
Here is what I think is happening inside the getCards() function: 我认为这是在getCards()函数内部发生的事情:
getCards()
declared with a return type of void getCards()
方法,其返回类型为void getCards()
method getCards()
方法 .subscribe()
to listen for changes to that data .subscribe()
侦听对该数据的更改 c => this.cardlist = c
says for every card c
passed in from the service add it to cardlist
c => this.cardlist = c
表示从服务传入的每张卡c
将其添加到cardlist
Clearly I'm wrong about step 4. What did I do wrong? 显然,我对步骤4错误。我做错了什么?
Working tutorial code (reproduced for convenience): 工作教程代码(为方便起见而复制):
import { Component, OnInit } from '@angular/core';
import { Hero } from '../hero';
import { HeroService } from '../hero.service';
@Component({
selector: 'app-heroes',
templateUrl: './heroes.component.html',
styleUrls: ['./heroes.component.css']
})
export class HeroesComponent implements OnInit {
selectedHero: Hero;
heroes: Hero[];
constructor(private heroService: HeroService) { }
ngOnInit() {
this.getHeroes();
}
onSelect(hero: Hero): void {
this.selectedHero = hero;
}
getHeroes(): void {
this.heroService.getHeroes()
.subscribe(heroes => this.heroes = heroes);
}
}
You are missing few paranthesis, try it as follows, 您缺少一些括号,请尝试以下操作,
getHeroes(): void {
this.heroService.getHeroes()
.subscribe(resUserData => {
this.heroes = resUserData
});
}
export class CardComponent implements OnInit {
cardlist = Card[];
....
getCards(): void {
this.cardService.getCards()
.subscribe(c => { this.cardlist = c);
});
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.