I am looking to create a service that can notify my components when there are any changes to the 'idCustomer' property. These changes should trigger certain actions in different components. Currently, I am using console.log to check if the change is received, but it only works for one component. As a newcomer to Angular, I would appreciate suggestions on a more efficient way to communicate the 'idCustomer' property between components. The 'Section' and 'Customer' components are siblings.
LoginService
idCustomerChanged = new Subject<string>();
constructor(private http: HttpClient) { }
login(requestBody: any): Observable<ResponseBody> {
return this.http.post<ResponseBody>(`${this.apiServerUrl}/Customer/GetCustomerLogin`, requestBody);
}
addIdCustomer(idCustomer: string) {
this.idCustomer = idCustomer;
this.idCustomerChanged.next(this.idCustomer);
}
removeIdCustomer() {
this.idCustomer = '';
this.idCustomerChanged.next(this.idCustomer);
}
getIdCustomer() {
return this.idCustomer;
}
LoginComponent (responsible for changing the 'idCustomer')
submit() {
if (this.form.valid) {
this.loginService.login(this.form.value).subscribe((response) => {
if (response.data) {
this.loginService.addIdCustomer(response.data[0].idCustomer);
this.router.navigate(['/products']);
} else {
this.error = 'Invalid Credentials';
}
});
}
}
NavBarComponent (displays the message)
idCustomer: string = '';
subscription: Subscription;
constructor(private loginService: LoginService, private router: Router) {
this.subscription = this.loginService.idCustomerChanged.subscribe((idCustomer) => {
this.idCustomer = idCustomer;
console.log(this.idCustomer + ' from nav-bar');
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
CustomerComponent (does not display the message)
idCustomer: string = '';
submenusCustomer = ['Profile', 'History', 'Account Payables'];
subscription: Subscription;
constructor(private loginService: LoginService) {
this.subscription = this.loginService.idCustomerChanged.subscribe((idCustomer) => {
this.idCustomer = idCustomer;
console.log(this.idCustomer + ' from customer-page');
});
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
SectionComponent (also does not display the message)
idCustomer: string = '';
subscription: Subscription;
constructor(private loginService: LoginService) {
this.subscription = this.loginService.idCustomerChanged.subscribe((idCustomer) => {
this.idCustomer = idCustomer;
console.log(this.idCustomer + ' from seccion-page');
});
}
ngOnInit(): void {
}
ngOnDestroy() {
this.subscription.unsubscribe();
}