Reputation: 253
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. :)
Upvotes: 0
Views: 689
Reputation: 55443
constructor(public sidebarService: SidebarService) {
this.subscription = this.sidebarService.sidebarEvent$.subscribe((data)=>{
this.toggleSidebar(data);
});
}
Upvotes: 1