【发布时间】:2018-07-23 11:59:47
【问题描述】:
我正在学习来自here 的教程,但我正在尝试通过使用“card”而不是“hero”来稍微调整 heros.component.ts 类。当我尝试拨打 .subscribe() 时,我得到了
src/app/card/card.component.ts(12,19) 中的错误:错误 TS1109:预期表达式。
我的版本(注意 cardlist 变量名称更改)
export class CardComponent implements OnInit {
cardlist = Card[]; //-------LINE 12
....
getCards(): void {
this.cardService.getCards() //--------LINE 19
.subscribe(c => this.cardlist = c);
}
}
这是我认为 getCards() 函数内部发生的事情:
- 方法
getCards()声明返回类型为 void - 调用cardService(在文件顶部导入)使用
getCards()方法 - 调用
.subscribe()以监听该数据的变化 - 此位:
c => this.cardlist = c表示从服务传入的每张卡c将其添加到cardlist
显然我对第 4 步有误。我做错了什么?
工作教程代码(为方便起见,转载):
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);
}
}
【问题讨论】:
-
原来是语法错误
cardlist = Card[];应该是cardlist: Card[];
标签: angular