Within my application, I have defined two modules named AppModule and UserModule.
I am currently encountering an issue with data sharing between the AppComponent and the LoginComponent (which belongs to the UserModule).
Below is a snippet of app.component.html:
<ul class="nav navbar-nav lg-nav visible-lg visible-md">
<li><a routerLinkActive="nav-active" routerLink="/page1">page1</a></li>
<li><a routerLinkActive="nav-active" *ngIf="!loggedIn" routerLink="/user/login">Login</a></li>
</ul>
Here is the implementation in app.component.ts:
import { MessageService } from './services/message.service';
export class AppComponent {
loggedIn = false;
constructor(private ms: MessageService, private cd: ChangeDetectorRef) {
this.ms.getMessage().subscribe(data => {
console.log('messageService: ', data);
if (data === 'login') {
this.loggedIn = !this.loggedIn;
this.cd.detectChanges();
}
});
}
}
Additionally, here is how login.component.ts is implemented within the UserModule:
constructor(
private ms: MessageService
) {}
-> call to login service
-> on success response
this.ms.sendMessage('login');
Lastly, the message.service.ts functionality:
import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';
@Injectable()
export class MessageService {
private message = new Subject<any>();
constructor() {}
sendMessage(message) {
this.message.next({ message: message });
}
clearMessage() {
this.message.next();
}
getMessage() {
return this.message.asObservable();
}
}
The main issue lies in the fact that the observer is not being subscribed in app.component.ts. I attempted utilizing the MessageService in a shared module but without success. How can I ensure that the message sent from LoginComponent (UserModule) reaches AppComponent when a user logs in, causing the Login Button to disappear?