0

I've a simple component which encapsulates a router-outlet. I've setup a simple service which emits a event. This event is captured by the component and updates variable, which then updates [class] in view.

Sidebar.component.ts

import { Component, OnInit } from '@angular/core';
import { ROUTER_DIRECTIVES } from '@angular/router';
import { SidebarService } from '../sidebar.service';
import { Subscription } from 'rxjs/Subscription';

@Component({
  moduleId: module.id,
  selector: 'app-sidebar',
  templateUrl: 'sidebar.component.html',
  styleUrls: ['sidebar.component.css'],
  directives: [ROUTER_DIRECTIVES]
})

export class SidebarComponent implements OnInit {
  showSidebar:boolean = false;
  subscription:Subscription;

  constructor(public sidebarService: SidebarService) {
    this.subscription = this.sidebarService.sidebarEvent$.subscribe(this.toggleSidebar);
  }

  ngOnInit() {

  }

  toggleSidebar (state) {
    console.log(state);
    this.showSidebar = state;
  }
}

sidebar.service.ts

import { Injectable, EventEmitter } from '@angular/core';
import {BehaviorSubject} from 'rxjs/BehaviorSubject';

@Injectable()
export class SidebarService {

  private _sidebarEventSource = new BehaviorSubject<boolean>(false);
  sidebarEvent$ = this._sidebarEventSource.asObservable();
  constructor() { }

  open () {
    this._sidebarEventSource.next(true);
  }

  close () {
    this._sidebarEventSource.next(false);
  }

}

I tried this: Angular2: view is not updated from inside a subscription.

Error: ORIGINAL EXCEPTION: TypeError: Cannot read property 'run' of undefined

I've scaffold my app using ng-cli.

Needless to say, I'm completely new to angular2, and had a background in ng1. So these style of coding, looks a new world to me.

And, btw, thanks for stopping by. :)

Community
  • 1
  • 1
ankitjain11
  • 253
  • 2
  • 16

1 Answers1

1
constructor(public sidebarService: SidebarService) {
    this.subscription = this.sidebarService.sidebarEvent$.subscribe((data)=>{
        this.toggleSidebar(data);
   });
}
micronyks
  • 54,797
  • 15
  • 112
  • 146
  • Thanks. It worked. But can you explain why earlier, the function was calling and console output was coming. But, the view was not updating? – ankitjain11 Jul 30 '16 at 08:29
  • Check the console with previous code again. I feel like it was not getting changed every time. – micronyks Jul 30 '16 at 08:32