I am trying to work across modules - I have written a service in a module
sharedService
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class SharedService {
private paramsSource = new Subject<any>();
current_params$ = this.paramsSource.asObservable();
set_current_params( params:any) {
this.paramsSource.next(params);
}
get_current_params(){
console.log(this.current_params$)// returns {'id':'15'} on console
return this.current_params$
}
I call this from a parallel module where I am able to set current params by using calling the service through the constructor. However, the getter does not seem to work from the same module. The subscription does not seem to work. It seems to return an observable but i am unable to subscribe to it.
my component.ts
import { Component, OnDestroy } from '@angular/core';
import { SharedService } from '../../../core/shared/shared.service';
import { Subscription, Observable } from 'rxjs';
@Component({
selector: '[app-myComponent]',
templateUrl: './myComponent.component.html',
styleUrls: ['./myComponent.component.scss']
})
export class MyComponentComponent implements AfterViewInit {
constructor(
private shared: SharedService
) { }
ngOnInit() {
this.shared.set_current_params({'id':'15'});
{
ngAfterViewInit() {
console.log(this.sharedService.get_current_params());//log line 1
this.shared.get_current_params().subscribe(current_params => {
console.log('anything'); //log line 2
console.log(current_params); //log line 3
})
}
Log line 1 returns an observable on the first line However, The subscribe returns nothing, and logs 2 and 3 are empty .
I try the same subscription from a different module, the getter also works. Why is it not getting picked up in this component just in the getter?
The issue is that you are setting a value before you are subscribing to it. If you move the code from ngOnInit
to ngAfterViewInit
and move the code from ngAfterViewInit
to ngOnInit
, then your subscription will work. See StackBlitz example. As mentioned in my comment above, if you need to support the ability to get the latest value upon subscription, i.e. the last value that was emitted before you subscribed, then you need to use either a BehaviorSubject or a ReplaySubject instead of Subject.