1

I'm finding my way through Angular 2, but I'm having a little trouble understanding the results that I'm getting from console.log when calling .subscribe within ngOnInit(). (Apologies in advance - I have practically zero experience with Angular and I am trying to jump into the middle of someone else's project - please forgive me if I do not quite explain this correctly)

In brief summary, if I console.log(this), I get an object with a members property that is an array - however, if I console.log(this.members), I get undefined.

In group-form.component.ts, I call

ngOnInit() {
     this.memberService.getMembers().subscribe(
         members => this.members = members.map(x => new Member(x))
         error => this.errorMessage = <any>error
         () => console.log(this))
};

And, pleasingly, this logs

GroupFormComponent
    model: Group
    members: Array[5]
    memberService: MemberService
    submitData: EventEmitter
    submitted: false
    __proto__: Object

However, if I change it to log this.members like so:

ngOnInit() {
     this.memberService.getMembers().subscribe(
         members => this.members = members.map(x => new Member(x))
         error => this.errorMessage = <any>error
         () => console.log(this.members))
};

this logs undefined.

I'm not sure that I understand why this is happening, since the log is being called at the same place in the chain of events. Why should .members have content when viewed as part of the object, but be undefined when viewed on its own?

And how can I get it to set and log the correct values?

K Scandrett
  • 16,390
  • 4
  • 40
  • 65
skwidbreth
  • 7,888
  • 11
  • 58
  • 105
  • That's not angular issue. There are multiple reasons this could be happening and you don't give enough information to actually know what's wrong so I recommend to just go through answers here and see what works for you. http://stackoverflow.com/questions/17546953/cant-access-object-property-even-though-it-exists-returns-undefined – Erndob Dec 10 '16 at 23:21
  • @Erndob ok thank you, will check that out. – skwidbreth Dec 11 '16 at 00:24

0 Answers0