vsharper
vsharper

Reputation: 317

Angular 2 service subscription not subscribing to my variable

My service is returning an array of objects, I’m trying to subscribe the response to my local variable “destinations”. Here is my code:

export class Component implements OnInit {

  destinations = [];

  constructor(public myService: MyService) {
  }

  ngOnInit() {
    this.myService.getDestinations()
        .subscribe(data => {
          destinations = data
       });
  }

}

Upvotes: 0

Views: 231

Answers (2)

Wesley Coetzee
Wesley Coetzee

Reputation: 4848

export class Component implements OnInit {

  destinations: string[] = [];

  constructor(public myService: MyService) {
  }

  ngOnInit() {
    this.myService.getDestinations()
        .subscribe(data => {
          this.destinations = data
       });
  }

}

Assuming you're getting an array back. You were missing two this:

first was: destinations: string[] = [];

second: this. in front of destinations, so this.destinations = data;

This should work correctly.

Upvotes: 1

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657841

this. is missing

this.destinations = data

Upvotes: 0

Related Questions