andrey.shedko
andrey.shedko

Reputation: 3238

Angular 2. Observable is not defined

I'm trying to use Observable and ChangeDetectionStrategy in order to inform the others components about changes happend. Unfortunately Observable object addItemStream is undefined. What is wrong here?

import { Component, ChangeDetectionStrategy, ChangeDetectorRef, Input }          from '@angular/core'
import { ROUTER_DIRECTIVES, Router }  from '@angular/router';
import {Observable} from 'rxjs/Observable';

@Component({
    selector: 'bp-header',
    templateUrl: 'app/header.component.html',
    directives: [ROUTER_DIRECTIVES],
    changeDetection: ChangeDetectionStrategy.OnPush
})
export class HeaderComponent {
    @Input() addItemStream: Observable<any>;
    public isActive: number;
    public language: string = "en";
    constructor(private cd: ChangeDetectorRef) {}
    ngOnInit() {
        this.isActive = 1;
     }
    ngAfterViewInit() {
    this.addItemStream.subscribe(() => {
        this.setLanguage; // application state changed
        this.cd.markForCheck();
       })
    }
    public setLanguage = (language: string) => {
        if (this.language === language) { return }
        else { this.language = language };
    }
    public setActive(active: number) {
        if (this.isActive === active) return;
        this.isActive = active;
    }
}

Upvotes: 1

Views: 3322

Answers (2)

Ben Richards
Ben Richards

Reputation: 3575

It doesn't matter where you subscribe to it. I usually do it in the constructor. However, when the component initializes first the stream is undefined so just initialize it in your constructor:

constructor(private cd: ChangeDetectorRef) {
  this.addItemStream = new Observable<any>();
}

Upvotes: 1

hholtij
hholtij

Reputation: 2936

You are subscribing to the Observable in ngOnInit. Since it is an Input the Observable (and all other Inputs) will be undefined at that point.

Try subscribing to it in ngAfterViewInit. Alternatively, put in a service. That makes your life (and sharing the Observable) a lot easier.

Upvotes: 2

Related Questions