使用 typescript 服务和可观察对象:为什么我的事件处理程序不会 运行?

working with typescript services and observables: why won't my event handler run?

我正在处理一个 Angular 2 项目。我正在尝试使用打字稿中的可观察对象和服务。我正在触发一个事件,但我的 observable 中的事件处理程序不是 运行ning.

这是我的代码:

服务:

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

@Injectable()
export class AllDataPageService {

    receptorFilterChanged$ = new Subject<any>();

}

该服务由一个事件组成:receptorFilterChanged。

这是触发事件的组件(位于 ~\src\results\app\all-data-page)

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

...

}

...

}

所以是上面函数 filterByReceptorTag() 中的 this.allDataPageService.receptorFilterChanged$.next(50.0) 行触发了事件。我已在 Chrome 调试器中确认此行已执行。

这里是处理 receptorFilterChanged 事件的组件(位于~\src\results\app\shared\components\all-data-row)

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 触发时,我在上面订阅的事件处理程序不会 运行。

任何人都可以看到可能发生的事情吗?

谢谢。

Can anyone see what might be going on?

时间问题。 subscribenext 之后发生,所以没有得到原始值

您的 "AllDataPageService" 的范围同时适用于 AllDataPageComponent 和 AllDataRowComponent。这意味着这些组件中的每一个都获得了该 AllDataPageService 服务的一个新实例。

您应该删除

providers: [AllDataPageService]

从您的每个组件并将其移至 "Module"。这样一来,您将只有一个服务实例,这样他们就可以相互交谈。