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、立ち寄ってくれてありがとう。 :)
ありがとう。出来た。しかし、なぜ早く機能が呼び出され、コンソールの出力が来るのか説明できますか?しかし、ビューは更新されていませんでしたか? – ankitjain11
前のコードでコンソールを再度確認してください。毎回変わっていないような気がします。 – micronyks