Rilcon42
Rilcon42

Reputation: 9763

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'. When I attempt to call .subscribe() I am getting

ERROR in src/app/card/card.component.ts(12,19): error TS1109: Expression expected.

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:

  1. method getCards() declared with a return type of void
  2. calls the cardService (imported at top of file) to use the getCards() method
  3. calling .subscribe() to listen for changes to that data
  4. this bit: c => this.cardlist = c says for every card c passed in from the service add it to cardlist

Clearly I'm wrong about step 4. What did I do wrong?


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);
  }
}

Upvotes: 0

Views: 394

Answers (2)

Dulanga Heshan
Dulanga Heshan

Reputation: 1425

export class CardComponent implements OnInit {

  cardlist = Card[];

   ....  
getCards(): void {
    this.cardService.getCards()
        .subscribe(c => { this.cardlist = c);
  });
}

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222582

You are missing few paranthesis, try it as follows,

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

Upvotes: 2

Related Questions