Reputation: 12503
For reasons beyond the scope of this question, I have had to stop using @injectable
. I converted my services that use it, just manually newing them up rather than using @injectable
and it works for all services except for my service that uses subscribe
My service that uses subscribe did work before I had to remove @injectable
. Can I get it to work without @injectable
?.
Code:
Service:
import { Subject } from 'rxjs/Subject';
export class ResultSelectionService {
// Observable string sources
private resultSelectedSource = new Subject();
// Observable string streams
resultSelected$ = this.resultSelectedSource.asObservable();
// Service message commands
selectResult(result: any, place: any) {
this.resultSelectedSource.next({result: result, place: place});
}
}
service user (the selectResult function does execute - Good):
//arrow function because when called above "this" is an html element
resultClick = (event) => {
this.resultSelectionService.selectResult(event.data.result, event.data.place);
}
method that should execute but does not ( code never gets inside result => {
:
constructor( ) {
this.resultSelectionService = new ResultSelectionService();
this.resultSelectionService.resultSelected$.subscribe(
result => {
this.selectedResult = { result };
$('#result-details-modal').appendTo("body").modal('show');
$('#result-details-modal').on('shown.bs.modal', (e) => {
this.resizeMap();
this.canGetAddress = true;
this.addMarkersToMap(this.map);
//this.bindAutoCompleteToMap();
})
console.log(this.selectedResult.result);
});
}
Can I get the subscribed function to execute without using @injectable
? If not, how can I work around this, creating something similar?
Upvotes: 0
Views: 2542
Reputation: 8731
What you need here is a single instance of ResultSelectionService
, that's why your subscribe method is never called.
You need to add @Injectable()
on ResultSelectionService
, add it in your forRoot()
module method (or directly in AppModule
's providers if it's the only module you have) and use it like that:
constructor( private resultSelectionService:ResultSelectionService ) {
this.resultSelectionService.resultSelected$.subscribe(
result => {
this.selectedResult = { result };
$('#result-details-modal').appendTo("body").modal('show');
$('#result-details-modal').on('shown.bs.modal', (e) => {
this.resizeMap();
this.canGetAddress = true;
this.addMarkersToMap(this.map);
//this.bindAutoCompleteToMap();
})
console.log(this.selectedResult.result);
});
}
This way, you'll be sure that only one instance of your ResultSelectionService
is provided everywhere in your app, and you'll be able to trigger the observable from anywhere.
Upvotes: 3