2016-06-11 24 views
1

Plunkrを実行していないサブスクライブします。 subscribeメソッドは何らかの理由で有効化されず、notifyAboutChangeが実行され、正しいIDが渡されますが、nextを呼び出した後、subscribeメソッドは呼び出されてもそれを受け取っていないようです。角度2は

オブザーバーを含むサービス:加入する必要があります

constructor(private _elementRef: ElementRef, private _renderer: Renderer, private _api: ApiService) { 

    this.eventHandler = _renderer.listen(_elementRef.nativeElement, ('ontouchstart' in window ? 'touchend' : 'click'), (e) => { 

    this.isAllChecked = !this.isAllChecked; 

    for (let checkbox of this.checkboxes) { 

     if (!checkbox.isDisabled) { 
     checkbox.isChecked = this.isAllChecked; 
     } 
    } 

    _api.notifyAboutChange(this.componentId); 
    }); 
} 

コンポーネント:notifyAboutChangeメソッドを呼び出します

import {Injectable} from '@angular/core'; 
import {Subject} from 'rxjs/Subject'; 

@Injectable() 

export class ApiService { 
    public notifier = new Subject(); 
    public changeOccurrence$ = this.notifier.asObservable(); 

    constructor() {} 

    notifyAboutChange(id: string) { 
    this.notifier.next(id); 
    } 
} 

指令

export class FormCheckboxMultipleComponent implements OnInit, DoCheck { 
    @Input() model: Array<any>; 
    @Input() checkboxes: Array<any>; 
    @Output('modelChange') onModelChange: EventEmitter<any> = new EventEmitter(); 
    @Output() callback: EventEmitter<any> = new EventEmitter(); 

    constructor(private _globals: GlobalVariablesService, private _differs: IterableDiffers, private _api: ApiService) { 
    this.ns = _globals.ns; 
    this.differ = _differs.find([]).create(null); 

    _api.changeOccurrence$.subscribe(
     componentId => { 
     console.log(componentId); 
     if (this.componentId === componentId) { 

      for (let checkbox of this.checkboxes) { 

      let existingIndex = this.findIndex(checkbox, this.model); 

      if (existingIndex === -1) { 
       this.model.push(checkbox); 
      } 
      else { 
       this.model.splice(existingIndex, 1); 
      } 
      } 
     } 
     } 
    ) 
    } 

    .... excluded parts .... 
} 

答えて

2

を、私はそれができると思いますサービスの同じインスタンスを共有しないためです。あなたのアプリケーションをブートストラップするときは、対応するプロバイダを定義することができます:

bootstrap(AppComponent, [ ApiService ]); 

は、コンポーネント/ディレクティブのproviders属性からサービスを削除することを忘れないでください。

必要に応じて、サービスの範囲を制限できます。たとえば、コンポーネントとディレクティブの両方を含む/使用するコンポーネントで定義することによって、

このplunkr:https://plnkr.co/edit/lGgNq5HpqFZCQfGl0Tpw?p=previewを参照してください。それではないです

+0

のHMなし:https://plnkr.co/edit/lGgNq5HpqFZCQfGl0Tpw?p=preview:/ – Chrillewoodz

+1

ます。また、コンポーネント/ディレクティブの 'providers'属性からサービスを削除する必要があります... –

+0

はこのplunkrを参照してください。 –