我是一个封装router-outlet
的简单组件。我设置了一个发出事件的简单服务。此事件由组件和更新变量捕获,然后在视图中更新[class]。
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);
}
}
我试过了:Angular2: view is not updated from inside a subscription。
Error: ORIGINAL EXCEPTION: TypeError: Cannot read property 'run' of undefined
我使用ng-cli
来支持我的应用。
毋庸置疑,我对angular2非常陌生,并且在ng1中有背景。所以这些编码风格对我来说是个新世界。
顺便说一句,谢谢你的到来。 :)
答案 0 :(得分:1)
constructor(public sidebarService: SidebarService) {
this.subscription = this.sidebarService.sidebarEvent$.subscribe((data)=>{
this.toggleSidebar(data);
});
}