Reputation: 937
i need to refresh header component after the user successfully log into the system. because i need to check user token null or not. I called that function inside the ngOninit() function. Please check my below header component code
export class HeaderComponent implements OnInit {
newUserMenu = true;
loginUserMenu = false;
constructor(private authService: AuthService, private routers: Router) {}
ngOnInit() {
this.isTokenAvailabe();
}
logout() {
localStorage.clear();
this.routers.navigate(['/login']);
}
isTokenAvailabe() {
console.log(this.authService.getJWTToken() );
if (this.authService.getJWTToken() === null) {
this.newUserMenu = true;
} else {
this.newUserMenu = false;
this.loginUserMenu = true;
}
}
}
My problem is, isTokenAvailabe() function did not update. because that header component not reload or refresh. Therfore ngOnInit() function not load. How i update it?
Upvotes: 0
Views: 1601
Reputation: 811
You can achieve this using BehaviourSubject
Observable
. That allows you to push latest value to another component and in another component you will be subscribing(listening for change) to update the value.
In your service.ts
you can do like this
import { BehaviorSubject } from 'rxjs';
private messageSource = new BehaviorSubject('default message');
public currentMessageSubscriber = this.messageSource.asObservable();
notify(message: any) {
this.messageSource.next(message)
}
And in your login.component.ts
you can call notify()
in login
api
response like this
this.dataService.login(loginObject).subscribe(res=>{
this.dataService.notify({isRefresh : true});
})
Finally inside your header.component.ts you can subscribe for getting update in ngOnInit
like this
ngOnInit() {
this.__dataService.currentMessageSubscriber.subscribe((data : any)=>{
if(data.isRefresh ){
this.isTokenAvailabe();
}
})
}
In this way when you receive login
response so instantly you will notify another component that hey check for the token. And inside your header.component.ts
you can subscribe for getting the msg to update instantly.
Upvotes: 3