0

I have a method that is subscribing to an event from a pub sub messaging service. In the callback I am wanting to define a class property. When I try to assign the property value, it returns as undefined. I understand that the reference to 'this' changed from the class to the method, but I need it to have access to the class's 'this' property. How can I assign the value to the class property 'this.icon' inside my callback method?

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs/Subscription'
import { Events } from '../shared/messages/events';
import { MessageService } from '../shared/messages/message.service';

export class Component implements OnInit, OnDestroy {

  public icon: string;
  private subscription: Subscription;

  constructor() { this.btnClickSubscribe();}

  private btnClickSubscribe(): void {

     this.subscription = this.messageService
        .subscribe(Events.btnClick, (payload) => {

        this.icon = 'fa-trash-o'; 

        console.log(this.icon) //logs the correct value, 'fa-trash-o' 
        //but it's only available inside this context. I need it in the 
        //class context     
  });
 }
Austin
  • 115
  • 1
  • 10
  • Why do you assign the callback? – Roman C Apr 25 '17 at 19:08
  • I'm binding to a child component's css class and passing the string as the value. I need to assign the value to this.icon but it's returning as undefined when I pass it to the child component. I have tested everything, and the problem is here. When I hard code a string to the child component it works fine. I'm tripped up when trying to do it this way, programatically. – Austin Apr 25 '17 at 19:13
  • What happens when you use `ngOnInit()` instead of `constructor` to make the call to `this.btnClickSubscribe();`? http://stackoverflow.com/questions/35763730/difference-between-constructor-and-ngoninit – adam-beck Apr 25 '17 at 19:17
  • Same thing, undefined. – Austin Apr 25 '17 at 19:20

1 Answers1

0

Since this is an asynchronous event, this.icon will initially be undefined outside the callback, no matter what you do. Check this one about more info: How do I return the response from an Observable/http/async call in angular2?

You mentioned you are passing icon to a child via @Input() then make use of ngOnChanges in the child, which captures the changes happening to icon. In the ngOnChanges you can make a condition, that executes whatever logic you want to do, after the value has been set to to icon, so something like this in your child:

@Input() icon;

ngOnChanges() {
  if(this.icon) {
    console.log('icon is set, now do something with it!')
  }
}

And if you have problems with the view, there are some possible solutions, like using the safe navigation operator, more info here: Cannot read property "totalPrice" of undefined

Here's a

Demo

Hope this helps! :)

Community
  • 1
  • 1
AT82
  • 71,416
  • 24
  • 140
  • 167