【问题标题】:Angular assign objects in subscribe订阅中的角度分配对象
【发布时间】: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() 函数内部发生的事情:

  1. 方法 getCards() 声明返回类型为 void
  2. 调用cardService(在文件顶部导入)使用getCards()方法
  3. 调用.subscribe() 以监听该数据的变化
  4. 此位: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


【解决方案1】:

你少了几个括号,试试如下,

   getHeroes(): void {
        this.heroService.getHeroes()
        .subscribe(resUserData => {
            this.heroes = resUserData
          });
    }

【讨论】:

    【解决方案2】:
    export class CardComponent implements OnInit {
    
      cardlist = Card[];
    
       ....  
    getCards(): void {
        this.cardService.getCards()
            .subscribe(c => { this.cardlist = c);
      });
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-11-21
      • 2021-01-10
      • 2020-12-18
      • 2018-08-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多