How to make http post call inside route guard in angular7?

﹥>﹥吖頭↗ 提交于 2020-03-06 09:21:08

问题


I have an Angular 7 app in which I have a post call and on the basis of that post call response I want to make guard active/inactive. I have my route guard like this

canActivate = (_router: ActivatedRouteSnapshot): boolean => {
    console.log('in link expiry guard')
    let userEmail = _router.paramMap.get('email');
    let isAllow;

    console.log('params : ', userEmail)
    userEmail = this._utilityService.decryptMsgByCryptoJs(userEmail);
    console.log('user email : ', userEmail)
    this._dataService.post(this._const.userResetPasswordLinkExpiry, { email: userEmail }).subscribe(resp => {
        console.log('verify response : ',resp)
        if (resp.success) {
            console.log('in success')
            isAllow = true;
        } else {
            isAllow = false;
        }
    })
    console.log('allow flag  : ',isAllow)
    if (isAllow) {
        console.log('in allow')
        return true;
    } else {
        console.log('in not allow')
        this._utilityService.navigate('/login');
        this._dataService.exhangeResetPasswordObsMsg({ event: 'linkExpired' });
        return false;
    }
}

But problem is that while my http post call is being in progress so my guard executes completely and returning false and after that response is coming from post call. How can I manage this scenario so I will make route true or false based on http post call response.


回答1:


If you want to make an Http request inside your canActivate function, you need to return an Observable<boolean> instead of a boolean, since you are now performing an asynchronous action.

And since you want to navigate on fail, you should return Observable<boolean | UrlTree> instead.

Simple version

constructor(private router: Router) { }

canActivate(route: ActivatedRouteSnapshot, 
    state: RouterStateSnapshot): Observable<boolean | UrlTree> {
  return this.http.post(url, body).pipe(
    map((resp: any) => resp.success ? true : this.router.parseUrl('/path'))
  );   
}

We are returning the observable http request (the router will invoke it by subscribing), and mapping the response to either a

  • true - the router may proceed to the guarded route
  • UrlTree - the router should navigate to the route we have returned

Applied to your example

If we apply this to your example, we need to do a bit more work in the pipe, as you have an additional service call.

// TODO: inject other services
constructor(private router: Router) { }

canActivate(route: ActivatedRouteSnapshot, 
      state: RouterStateSnapshot): Observable<boolean | UrlTree> {
    const userEmail = route.paramMap.get('email');

    // I am assuming this is a synchronous call
    userEmail = this._utilityService.decryptMsgByCryptoJs(userEmail);

    const url = this._const.userResetPasswordLinkExpiry;
    const body = { email: userEmail };

    return this._dataService.post(url, body).pipe(
      // initial map from response to true/false
      map((resp: any) => resp.success),

      // perform an action if false
      tap(success => {
        if (!success) {
          // I'm assuming this is synchronous. If not, you will need to do a switchMap
          this._dataService.exhangeResetPasswordObsMsg({ event: 'linkExpired' });
        }
      }),
      // final map to boolean | UrlTree
      map(success => success ? true : this.router.parseUrl('/login'))
    );   
}

There are some service calls in there that I'm assuming are synchronous. This answer demonstrates how you perform an asynchronous call inside canActivate and either allow the router to navigate or return an alternative route to navigate to.



来源:https://stackoverflow.com/questions/60402486/how-to-make-http-post-call-inside-route-guard-in-angular7

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!