2016-06-11 126 views
1

Plunkr:https://plnkr.co/edit/arROwxsFYraSBeAZCIYF?p=preview角2訂閱不執行

我想訂閱的觀察者,但我不能得到它的工作。訂閱方法從未被激活,出於某種原因,notifyAboutChange運行並且傳遞了正確的標識,但在調用next之後,訂閱方法似乎無法在被調用時啓用。

其中包含了觀察者的服務:

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); 
    } 
} 

指令,它調用notifyAboutChange方法:

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); 
    }); 
} 

組件應訂閱:

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

嗯沒有這不是它:/ – Chrillewoodz

+1

您還需要從'組件/指令providers'屬性刪除服務... –

+0

看到這個plunkr:https://plnkr.co/edit/lGgNq5HpqFZCQfGl0Tpw?p=preview –