This question has already been answered:
There is a user service in which work with the backend for authorization, registration, and so on is implemented.
The algorithm is as follows:
There is a method for obtaining a token from the LAN:
getToken() { this.token = this.storageService.get('token'); return true; }; And checking this token on the server side:
tokenVerify() { return this.http.post(this.verifyUrl, JSON.stringify({ token: this.token, } ),{headers: this.headers}) .toPromise() .then(response => { if(response.json().token == this.token) { this.headers.append('authorization', `JWT ${this.token}`); } }) .catch(this.handleError); }; In case of successful verification, the token will be included in all request headers.
As well as the authorization verification method
checkAuth() { if (this.getToken() && this.tokenVerify()) { return true; } else return false }; + There is a method to get a username through a token
getMyUserName(): Promise<ICatalogUser> { console.log('Получаем имя'); console.log(this.headers); return this.http.get(this.meUrl, {headers: this.headers}) .toPromise() .then(response => response.json() as ICatalogUser) .catch(this.handleError); }; The main problem is that the verification method of the token is asynchronous and the method for obtaining the name is asynchronous and when I try to verify the authorization in the component and get the user name, nothing happens because there is no token yet during the verification:
ngOnInit(): void { this.getPosts(); this.checkAuth(); this.user = this.userService.me; } Please tell me how best to solve this problem?