I'm working with an Angular 2 project. I'm trying to work with observables and services in typescript. I am firing an event but the event handler in my observable is not running.
Here is my code:
The Service:
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs/Subject';
@Injectable()
export class AllDataPageService {
receptorFilterChanged$ = new Subject<any>();
}
The service consist of one event: receptorFilterChanged.
Here is the component that fires the event (located at ~\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);
...
}
...
}
So it's the line this.allDataPageService.receptorFilterChanged$.next(50.0) in the function filterByReceptorTag() above that fires the event. I have confirmed in the Chrome debugger that this line executes.
Here is the component that handles the receptorFilterChanged event (located at ~\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) => {
...
}
);
}
...
}
When the receptorFilterChanged fires, the event handler that I subscribe above does not run.
Can anyone see what might be going on?
Thanks.
Your "AllDataPageService" is scoped to both the AllDataPageComponent and also the AllDataRowComponent. That means each of these components gets a new instance of that AllDataPageService service.
You should remove the
providers: [AllDataPageService]
from each of your components and move it to a "Module" instead. That way, you'll only have one instance of your service so they'll be able to talk to each other.