首页 > 解决方案 > Angular 服务内的所有身份验证逻辑

问题描述

我想在 auth 服务中移动所有业务逻辑,在组件方面我只想调用该方法因为我的函数都没有返回任何内容,这样可以吗?或者它们会挂起吗?

零件

  credentials: Credentials = {
    email: 'pacurarudaniel@gmail.com',
    password: '123'
  }

  onLogIn(): void {
    this.authService.logIn(this.credentials.email, this.credentials.password);
  }

服务

  public logIn(email: string, password: string): void {
    this.http.post<any>('http://localhost:3100/login', { email, password })
      .subscribe(user => {
        localStorage.setItem('TOKEN', user.token)
        this.router.navigateByUrl('/home');
      });
  }

标签: angulartypescript

解决方案


您的服务方法不需要返回任何东西,它不会挂起。Angular 中的 HttpClient 使用 RxJs 工作,这是一种执行异步代码的方式。

您可以选择订阅(或将订阅返回)组件,而不是让您的组件能够根据需要取消。

如果你想订阅你的组件,你可以tap用来获取你需要的结果数据。

对我来说,这些方法中的任何一种都是设置代码的完全有效的方法。


推荐阅读