在ngx-restangular上注入路由器

时间:2017-10-17 16:16:45

标签: angular restangular

我使用ngx-restangular并且我想拦截响应,如果我得到403,我希望能够调用服务来刷新令牌或将用户重定向到登录页面。

AutneticationService构造函数:

constructor(private router: Router, private restangular: Restangular) {}

所以,我在app.module上发了这个:

    // This function must return observable
      var refreshAccesstoken = function () {

        let auth = new AuthenticationService(undefined, undefined);

        // Here you can make action before repeated request
        // This will throw an error
        // ERROR TypeError: Cannot read property 'one' of undefined
        // because refresh method uses a constructor dependencie (restangular to make the http request)
        return auth.refresh();
      };

      RestangularProvider.addErrorInterceptor((response, subject, responseHandler) => {

        if (response.status === 403) {

          // How to redirect user to login page or how to call the
          // refreshAccesstoken() function that will make the http call to get new token?

          refreshAccesstoken()
            .switchMap(refreshAccesstokenResponse => {
              //If you want to change request or make with it some actions and give the request to the repeatRequest func.
              //Or you can live it empty and request will be the same.

              // update Authorization header
              response.request.headers.set('Authorization', 'Bearer ' + refreshAccesstokenResponse)

              return response.repeatRequest(response.request);
            })
            .subscribe(
              res => responseHandler(res),
              err => subject.error(err)
            );

            return false; // error handled
          }
          return true; // error not handled
        });

这是AuthenticationService刷新功能:

refresh() {
        // First way of creating a this.restangular object.
        // Just saying the base URL.
        let baseAuth = this.restangular.one('api').one('refresh');

        return baseAuth.get();
    }

谢谢大家!

0 个答案:

没有答案