0
我有一個簡單的組件,它封裝了一個router-outlet
。我已經設置了一個簡單的服務,它發出一個事件。該事件由組件和更新變量捕獲,然後在視圖中更新[class]。Angular2:視圖不會在更改變量時更新
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中擁有背景。所以這些編碼風格,對我來說是一個新的世界。
而且,順便說一句,謝謝你停下來。 :)
謝謝。有效。但是,你能解釋爲什麼早些時候,函數正在調用並且控制檯輸出即將到來。但是,這個觀點並沒有更新? – ankitjain11
再次使用以前的代碼檢查控制檯。我覺得每次都沒有改變。 – micronyks