简体   繁体   English

如何使用 angular pipe 并在请求调用中正确订阅

[英]how to use angular pipe and subscribe correctly in request call

In my angular application I am sending a request to my backend to check credentials, after success the backend sends an token which I read.在我的 angular 应用程序中,我向后端发送请求以检查凭据,成功后后端发送一个我读取的令牌。 So far this works, but I had to use an pipe to make it map to a method and then make it work.到目前为止,这是有效的,但我必须使用 pipe 将它变成 map 到一个方法,然后使其工作。 But my problem now it even though I am getting 200 from the server my page will not navigate to the protected page automatically.但我现在的问题是,即使我从服务器获得 200,我的页面也不会自动导航到受保护的页面。 If I enter the url manually it works this is what I tried:如果我手动输入 url 它会起作用,这就是我尝试过的:

  authenticateUser(login: LoginModel){
    this.http = new HttpClient(this.handler)
    return this.http.post<JwtToken>(environment.rootUrl + 'api/authenticate', {
      username: login.username,
      password: login.password,
    }).pipe(map(response => this.authenticateSuccess(response)))
      .subscribe({
        next: () => {
          this.isAuthenticated = true;
          this.router.navigate(['/dashboard'])
        }, error: (error) => {
          this.isAuthenticated = false;
          console.log(error)
        }
      })

  }

It does not enter the subscribe part after the pipe. Is there any way to make this work?它在pipe之后没有进入订阅部分。有什么办法可以使这个工作吗? I still want to have an error handling like if no error then navigate to url if error do not navigate.我仍然希望有一个错误处理,如果没有错误则导航到 url 如果错误不导航。

EDIT:编辑:

AuthenticateSuccess method:验证成功方法:

  isUserLoggedIn(){
    return !! localStorage.getItem('authenticationToken')
  }

  private authenticateSuccess(response: JwtToken): void {
      const jwt = response.id_token;
      localStorage.setItem('authenticationToken' , jwt)
      this.localStorageService.store('authenticationToken', jwt);
      console.log(this.localStorageService.retrieve('authenticationToken'))
      this.sessionStorageService.clear('authenticationToken');

  }

Authguard:授权卫士:

@Injectable({
  providedIn: 'root'
})
export class AuthGuard implements CanActivate {

  constructor(
    private auth: AuthenticationService,
    private router: Router
  ) {
  }

  canActivate(): Promise<boolean> {
    return new Promise(resolve => {
      if (this.auth.isUserLoggedIn()) {
        resolve(true)
      } else {
        this.router.navigate(['authenticate'])
        resolve(false)
      }
    })

  }
}

SOLUTION:解决方案:

 authenticateUser(login: LoginModel) {
    this.http = new HttpClient(this.handler)
    return this.http.post<JwtToken>(environment.rootUrl + 'api/authenticate', {
      username: login.username,
      password: login.password,
    }).subscribe({
      next: response => {
        this.isAuthenticated = true;
        this.authenticateSuccess(response)
        this.router.navigate(['/dashboard'])
      }, error: (err) => {
        console.log(err)
      }, complete: () => {
        console.log("finished without worry")
      }
    })
  }

RxJs map operator is supposed to modify the content of an observable. RxJs map运算符应该修改可观察对象的内容。 The map operator however needs to return the same observable or another observable, for the next subscribe operation to be able to function.然而, map运算符需要返回相同的可观察值或另一个可观察值,以便下一个subscribe操作能够 function。

In your case your map operator does not return any observable at all and therefore the subscribe method has no reason to be triggered.在您的情况下,您的map运算符根本不返回任何可观察值,因此没有理由触发subscribe方法。

You could simple return the response again in your method here您可以在此处的方法中再次简单地返回response

private authenticateSuccess(response: JwtToken): any {
      const jwt = response.id_token;
      localStorage.setItem('authenticationToken' , jwt)
      this.localStorageService.store('authenticationToken', jwt);
      console.log(this.localStorageService.retrieve('authenticationToken'))
      this.sessionStorageService.clear('authenticationToken');
      return response;
  }

but I think all the code of the map method matches better directly inside the subscribe method.但我认为map方法的所有代码直接在subscribe方法中匹配得更好。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM