我有一个封装了的简单组件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:订阅中的视图未更新。
Error: ORIGINAL EXCEPTION: TypeError: Cannot read property 'run' of undefined
我已经使用搭建了我的应用ng-cli
。
不用说,我是angular2的新手,并且具有ng1的背景。因此,这些编码风格对我来说是一个新世界。
而且,顺便说一句,谢谢您的光临。:)
constructor(public sidebarService: SidebarService) {
this.subscription = this.sidebarService.sidebarEvent$.subscribe((data)=>{
this.toggleSidebar(data);
});
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句