2016-07-30 16 views
0

私はrouter-outletをカプセル化する単純なコンポーネントを持っています。イベントを出すシンプルなサービスをセットアップしました。このイベントはコンポーネントおよび更新変数によって取得され、ビューで[クラス]を更新します。 Angular2: view is not updated from inside a subscription:私はこれを試してみました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); 
    } 

} 

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

ng-cliを使用して私のアプリをスキャフォールドしました。

言うまでもありませんが、私はangular2を全く新しくしていて、ng1の背景を持っていました。だからコーディングのこれらのスタイルは、私に新しい世界を見せます。

そして、btw、立ち寄ってくれてありがとう。 :)

答えて

1
constructor(public sidebarService: SidebarService) { 
    this.subscription = this.sidebarService.sidebarEvent$.subscribe((data)=>{ 
     this.toggleSidebar(data); 
    }); 
} 
+0

ありがとう。出来た。しかし、なぜ早く機能が呼び出され、コンソールの出力が来るのか説明できますか?しかし、ビューは更新されていませんでしたか? – ankitjain11

+0

前のコードでコンソールを再度確認してください。毎回変わっていないような気がします。 – micronyks

関連する問題