Угловой поток входа в систему 2 с вызовом localStorage и http api

Я довольно новичок в Angular 2, и в настоящее время я пытаюсь завершить процесс входа в систему. Я размещаю учетные данные пользователя в API и получаю токен JWT. затем я запрашиваю данные пользователя с этим токеном и сохраняю всю информацию в localStorage, но я не уверен, что это правильно, иногда у меня возникают проблемы.

метод входа

  login(user): Promise<any> {
localStorage.clear();
return this.http
  .post(`${this.url}/auth/login_check`, JSON.stringify(user), { headers: this.headers }).toPromise().then(resp => {
    let json = resp.json();
      if (json.token){
        console.log('token exists')
        localStorage.setItem('jwt_token', json.token);
        this.storeUser().then(resp => {
          console.log('user exists')
          return true;
        }, err => {
          this.handleError(err);
          return false;
        })
      }
      else {
        return false;
      }
    },
    err => {
      this.handleError(err);
      return false;
    })
  };

метод storeUser

  storeUser(): Promise<any> {
this.headers.append('Authorization', 'Bearer '+localStorage.getItem('jwt_token'));
console.log(this.headers);
return this.http.get(`${this.url}/users/0`, { headers: this.headers }).toPromise().then(resp => {
  let json = resp.json();

  let picture = 'data:image/jpeg;base64,/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDABEMDQ8NCxEPDg8TEhEVGiscGhgYGjUmKB8rPzdCQT43PDtFTmNURUleSzs8VnZXXmdqb3BvQ1N6g3lsgmNtb2v/2wBDARITExoXGjMcHDNrRzxHa2tra2tra2tra2tra2tra2tra2tra2tra2tra2tra2tra2tra2tra2tra2tra2tra2v/wAARCAGQAZADASIAAhEBAxEB/8QAGQABAAMBAQAAAAAAAAAAAAAAAAIDBAEG/8QAJhABAAICAQQBBQADAAAAAAAAAAECAxExEiFBUWETMnGBkSJCUv/EABQBAQAAAAAAAAAAAAAAAAAAAAD/xAAUEQEAAAAAAAAAAAAAAAAAAAAA/9oADAMBAAIRAxEAPwD14AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA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jwmAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAArtlivaO8gsQtkrHlTa9rcz+kQWzm9R/UfrW+EAE/q39n1b+0AFkZp8xCcZqzz2UANUTE8Tt1kiZjhZXNMfd3BeORaLRuJdAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAcmYrG5ly1orG5Z7Wm07kEr5Jt2jtCAAAAAAAAAAAARM1ncSvpki3ae0qAGsU48ni39XAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAI2tFY3LszqNyz3vNp+PAOWtNp3LgAAAAAAAAAAAAAAALcWT/Wf0qAaxXiv1RqeVgAAAAAAAAAAAAAAAAAAAAAAAAAAAIZLdNfnwCvNfc9MftWAAAAAAAAAAAAAAAAAAAETMTuOWmtotXbMnit0278SDQAAAAAAAAAAAAAAAAAAAAAAAAAAzZLdVvhblt0115lQAAAAAAAAAAAAAAAAAAAAAAC/FbqrrzCxmx26bb8NIAAAAAAAAAAAAAAAAAAAAAAAI3t01mQUZbdV/wiAAAAAAAAAAAAAAAAAAAAAAADRit1U+YZ1mG2ra9gvAAAAAAAAAAAAAAAAAAAAAAU5p4r+1zNknd5kEQAAAAAAAAAAAAAAAAAAAAAAACJ1OwBqidxt1XindNelgAAAAAAAAAAAAAAAAAAAAOWnVZllX5p1T8qAAAAAAAAAAAAAAAAAAAAAAAAAAAWYJ/ymPa9mxzq8NIAAAAAAAAAAAAAAAAAAAAKc88QqTzT/mgAAAAAAAAAAAAAAAAAAAAAAAAAAA1R3jbK00ndIBIAAAAAAAAAH//Z';

  localStorage.setItem('user_id', json.id);
  localStorage.setItem('user_username', json.username);
  localStorage.setItem('user_email', json.email);
  localStorage.setItem('user_enabled', json.enabled);
  localStorage.setItem('user_last_login', json.last_login);
  localStorage.setItem('user_roles', json.roles);
  localStorage.setItem('user_validated', json.validated);
  localStorage.setItem('user_picture', picture);
  console.log(localStorage.getItem('user_username'));
  return true;
},
err => {
  this.handleError(err);
  return false;
});

}

Метод входа в компонент входа

  signIn() {
this.processing = true;
this.active = true;
this.error = false;
this.success = false;

this.authSvc.login({ username: this.loginForm.value['username'], password: this.loginForm.value['password'] }).then(resp => {

  this.processing = false;
  this.success = true;
  this.router.navigateByUrl('');
}, err => {
  this.processing = false;
  this.error = true;
})

};

0 ответов

Другие вопросы по тегам