Hey everyone, I'm currently facing a challenge with Angular 6 and its components. I've created a service to facilitate communication between two components - triggering an event in one component should reload the other.
Here is the code for the CommunicationService:
import { Injectable } from '@angular/core';
import { Observable, BehaviorSubject} from 'rxjs';
@Injectable()
export class CommunicationService {
private subject = new BehaviorSubject<boolean>(false);
constructor() { }
public change(){
this.subject.next(true);
}
public getChange(): Observable<boolean>{
return this.subject.asObservable();
}
}
Next, here is the code for the Observable component:
public subscription: Subscription;
constructor(
private _router: Router,
private _communication: CommunicationService
){}
loginUser()
{
this._router.navigate(['./loginUser']);
this.subscription= Observable.interval(500).subscribe(x=>
{
this._communication.getChange().subscribe( resp=>{
if(resp===true){
this.ngOnInit();
this.subscription.unsubscribe();
}
})
});
}
Finally, take a look at the trigger component code:
this._communication.change();
In essence, the last component imports the Communication Service and calls the method change(). While debugging the code, everything appears correct but I always receive false as the response of the subscription, even when the change() method is called. What am I doing wrong?
UPDATE - ISSUE RESOLVED: Initially, my code was correct. The issue stemmed from incorrectly importing the service in both components within providers instead of importing it in the app module. It's now functioning properly.