After logging into my login component, I want to pass data to my navbar component but unfortunately, my navbar content does not update.
The navbar component is located in the app-module while the login component is in a separate module.
I attempted to use services to share the data between components.
In my login component, which resides in a different module:
export class LoginComponent {
userCredentials;
constructor(
private readonly _authService: AuthService,
) {
}
login() {
this._authService.auth(this.userCredentials)
.subscribe(
(response: any) => {
const dataForm = {
usuario: response.user,
rol: this.response.role,
};
this._authService.setSession(response);
},
error => {
console.log(error);
}
);
}
}
In my NavBarComponent, found within the app-module:
export class NavbarComponent {
isLogged = false;
susbscription: Subscription;
constructor(
private readonly _authService: AuthService,
) {
this.subscription = this._authService
.changeState$
.subscribe(
(isLogged) => {
this.isLogged = isLogged;
},
error => console.log(error)
);
}
}
Here is the HTML for my NavBar component:
<mat-toolbar color="primary">
<mat-toolbar-row>
<span>SUPERMERCADO</span>
<span class="spacer"></span>
<div *ngIf="!isLogged">
<button mat-button
Login
</button>
</div>
<div *ngIf="isLogged">
<p>Welcome</p>
</div>
</mat-toolbar-row>
</mat-toolbar>
The AuthService, which is not part of the app-module:
@Injectable()
export class AuthService {
protected url = environment.url;
protected model = '/user';
isLogged = false;
private changeState = new Subject<boolean>();
changeState$ = this.changeState.asObservable();
constructor(
private readonly _router: Router,
protected readonly httpclient: HttpClient,
) {
}
setSession(data: any) {
this.isLogged = true;
this.changeState.next(this.isLogged);
}
auth(dataForm: any): Observable<any> {
const url = `${this.url}${this.model}/login`;
return this.httpclient.post(url, dataForm);
}
}
This project is built using Angular 8.2.0.