I'm working with Angular5 as Front and Symfony as Backend.
I have a login function like this, which is working:
login(username: string, password: string): Observable<UserModel>
return this.globalHttp.post('login', {username,password}).subscribe(
data => {
const token = token.data;
this.setToken(token);
this.router.navigateByUrl("/profiles-list");
return Observable.of(data.user);
});
}
So the function logs me in by setting the token in localstorage.
But when the router navigate to /profiles-list, the token is still null.
profiles-list.component.ts
ngOnInit(){
this.profileService.getProfiles();
}
profile.service.ts
getProfiles(): Observable<ProfileModel[]>
{
return this.globalHttp.get('profiles',{});
}
global-http.service
token: string = localStorage.getItem('token') || null;
private _headers = {headers: new HttpHeaders().set('Authorization', 'Bearer ' + this.token).set('Content-Type' : 'application/json')};
get( url: string, data?: any): Observable<any>
{
return this.http.get(this.API_URL + url + this._headers)
}
I have to reload the page after login to make it work. What am I missing?
You have just declared token
in your service. So when the service is initialized, token has no value and it will never be updated "by itself". Just fetch the token inside your get
and set the headers:
get(url: string, data?: any): Observable<any> {
let token = localStorage.getItem('token') || null;
let headers = {headers: new HttpHeaders()
.set('Authorization', 'Bearer ' + token)
.set('Content-Type' : 'application/json')};
return this.http.get(this.API_URL + url + headers)
}
You could also move getting the token and setting headers in a separate method and just call that inside get
-method (and all other possible methods).