2

我正在使用 Angular8 并尝试制作登录表单。

我有一个 auth.service 我正在使用发布请求发送登录信息

auth.service.ts

login(form: FormData) {
    return this.httpClient.post<UserLogin>(`${this.AUTH_SERVER}/api/function.php`, form);
}

我有一个 login.component 它将获取表单数据并将其发送到服务

登录组件.ts

login() {
    const formData = new FormData();
    formData.append('action', this.loginForm.value.action);
    formData.append('email', this.loginForm.value.email);
    formData.append('password', this.loginForm.value.password);

    this.authService.login(formData).subscribe(
      (res) => {
        this.authService.isLoggedIn = true;
        localStorage.setItem('ACCESS_TOKEN', "isLoggedIn");
        this.router.navigateByUrl('/admin');
      },
      (err) => console.log('err', err)
    )
  }

我的问题是,在组件中、订阅中、获得成功的地方使用本地存储是否可行,或者是否应该在服务中?

如果它在服务中更安全,我怎样才能让它只在登录成功时设置令牌?

谢谢

4

3 回答 3

2

是的,最好在服务中处理令牌

在你auth.service.ts添加一个方法

setToken(token) {
    this.authService.isLoggedIn = true;
    localStorage.setItem('ACCESS_TOKEN', token);
}

在你的login.component.ts

login() {
    const formData = new FormData();
    formData.append('action', this.loginForm.value.action);
    formData.append('email', this.loginForm.value.email);
    formData.append('password', this.loginForm.value.password);

    this.authService.login(formData).subscribe(
        (res) => {
            this.authService.setToken(yourtoken);
            this.router.navigateByUrl('/admin');
        },
        (err) => console.log('err', err)
    )
}

我希望这个能帮上忙

于 2019-09-25T19:28:47.903 回答
1

我个人更喜欢仅在服务中使用本地存储,因为它确保我只通过我的服务更改值。这往往会使您的代码更易于维护,因为您只通过此服务而不是本地存储与您的令牌进行交互。

将令牌存储在 localStorage 中是足够安全的。我个人更喜欢在应用程序处于活动状态时使用相同的方式读取令牌,userService然后将其保存在内存中。您不能只使用服务,因为这会在页面重新加载时丢失令牌。

如果你想要一个关于如何实现这个的例子,我已经对我过去使用的内容做了一个要点。

于 2019-09-25T19:07:24.810 回答
0

You can declare a method in your service to set the token and call it on success of login. Not sure about security but creating a storageService for doing these types of works makes a good abstraction and it'll make your life easier while debugging in future.

于 2019-09-25T19:03:34.537 回答