Drilon Hametaj
Drilon Hametaj

Reputation: 140

Angular 8 not change header after navigate

i want to change header when user is logged in, but i'm not able. Redirect works good and the center of page change, but the header don't.

This is function when click Login button in auth component

 LoginFormSubmit(LoginForm){
return this.http.post(environment.laravel_api+'/login',LoginForm.value).subscribe(
  data => this.afterLogin(data) ,
  error => console.log(error)
);

}

afterLogin(data){

this.user.setSession(data['user']);
this.route.navigateByUrl('');

}

Here is my header component:

 session;
  constructor(private  user: UserService, private http: HttpClient, private route: Router) {

  }

  ngOnInit(): void {
    console.log("Dentro");
    this.session = this.user.getSession();
  }


  Logout(){
    localStorage.clear();
    this.afterLogout();
  }

  afterLogout(){
    this.route.initialNavigation();
  }

And here is the userserice:

 constructor() { }



  setSession(session_data){
    localStorage.setItem('session', JSON.stringify(session_data));

  }

  getSession(){
    return JSON.parse(localStorage.getItem('session'));

  }

Upvotes: 1

Views: 757

Answers (1)

Guerric P
Guerric P

Reputation: 31825

You have to implement something like this in your user service:

@Injectable()
class UserService() {

    private _session= new BehaviorSubject<any>({});

    setSession(session_data: string) {
        this._session.next(session_data);
    }

    get session() {
        return this._session.asObservable();
    }
}

Then in the HeaderComponent:

<button>{{ (userService.session | async).firstName }}</button>

Explanation: prefer not using localStorage to hold the session, as it may cause the Angular app to be out of sync with the backend (when the session expires). Prefer sending a cookie from the backend, and let the Angular app retrieve user info every time the app starts or is refreshed.

An Angular service is a singleton (one instance for the whole app) so it can hold a state and share it with any component. The BehaviorSubject helps notify the subscribers when the login state has changed.

Upvotes: 2

Related Questions