Angular2でSPAなシステム開発:serviceのデータを同期するならPromiseよりもEmitter、EmitterよりもObservable
誤用ということなのですが、Ionic2(というかAngular2)のserviceのデータを同期させるのは、EventEmitterを使うのがわかりやすいです。コードを読む人もObservableよりわかりやすいのでは無いでしょうか。
最初はこの中のngAfterContentCheckedとかngAfterViewCheckedを使って、serviceのget系メソッドを実行してみたのですが、初期ページを表示させてその後ページが1回遷移するだけで30回以上このイベントが呼ばれていました。そのたびにメソッドを呼んでいるのは余りにも無駄でパフォーマンスの無駄が大きいと思われました。
import {Injectable, EventEmitter} from 'angular2/core'; @Injectable() export class SettingsService { public hello:string = 'hello'; helloChange: EventEmitter<string> = new EventEmitter(); constructor() {} getHello(){ return this.hello; } setHello(str:string){ this.hello = str; this.helloChange.emit(this.hello); } }
これがemitする側のサービス。
this._helloSubscription = _settingsService.helloChange.subscribe((value) => { this.myhello = value; });
受ける側のページコンポーネント。これだけで同期できます。
参考にしたのはこのディスカッション。最初の方のドットルールでは値を反映させることはできませんでした。
javascript – updating variable changes in components from a service with angular2 – Stack Overflow





納得したらすぐにシェア!