2017-11-15 16 views
0

私はAngular 2プロジェクトで作業しています。私はオブザーバブルとサービスをタイプスクリプトで処理しようとしています。私はイベントを発生させていますが、私の観測可能なイベントハンドラは実行されていません。typescriptサービスとobservablesを操作する:なぜ私のイベントハンドラは実行されませんか?

サービス:

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

@Injectable() 
export class AllDataPageService { 

    receptorFilterChanged$ = new Subject<any>(); 

} 

サービスは、一つのイベントで構成されていますreceptorFilterChangedを

は、ここに私のコードです。ここで

イベント発火の成分である(のsrc \結果\〜に位置し、\アプリ\すべてのデータ・ページ)

import { AllDataPageService } from './all-data-page.service'; 

... 

@Component({ 
    selector: 'all-data-page', 
    templateUrl: './all-data-page.component.html', 
    styles: [require('./all-data-page.style.scss')], 
    providers: [AllDataPageService] 
}) 
export class AllDataPageComponent implements OnInit { 

... 

    constructor(private allDataPageService: AllDataPageService) {} 

... 

filterByReceptorTag() { 

... 

this.allDataPageService.receptorFilterChanged$.next(50.0); 

... 

} 

... 

} 

だから、ラインだthis.allDataPageService.receptorFilterChanged $ .next(50.0 )は、イベントを発生させる上記のfilterByReceptorTag()関数内にあります。 Chromeのデバッガで、この行が実行されていることを確認しました。ここ

は、(アプリ\は\コンポーネント\すべてのデータ列を共有\のsrc \結果\〜に位置する)receptorFilterChangedイベントを処理するコンポーネントである

import { AllDataPageService } from '../../../all-data-page/all-data-page.service'; 

... 

@Component({ 
    selector: 'all-data-row', 
    templateUrl: './all-data-row.component.html', 
    styles: [ require('./all-data-row.style.scss') ], 
    encapsulation: ViewEncapsulation.None, 
    providers: [AllDataPageService] 
}) 
export class AllDataRowComponent implements OnInit { 

... 

    constructor(private allDataPageService: AllDataPageService) { 
     this.allDataPageService.receptorFilterChanged$.subscribe(
      (value) => { 

... 

      } 
    ); 
    } 

... 

} 

場合receptorFilterChanged火災、イベントハンドラ私は上記の購読は実行されません。

何が起こっているのか誰にも見えますか?

ありがとうございました。

答えて

1

"AllDataPageService"は、AllDataPageComponentとAllDataRowComponentの両方にスコープされています。つまり、これらのコンポーネントのそれぞれは、そのAllDataPageServiceサービスの新しいインスタンスを取得します。

あなたはあなたのコンポーネントのそれぞれから

providers: [AllDataPageService] 

を削除し、代わりに「モジュール」に移動しなければなりません。そうすれば、サービスのインスタンスが1つしかないため、お互いに話すことができます。

+0

ビダルありがとうございました。 AllDataPageComponentからAllDataRowComponentにサービスを渡すとすぐに、サービスが開始されました。 – gib65

0

何が起こっているのでしょうか?

タイミング問題。 subscribenextの後に起きているので、元の値を取得しません。