角度函数 this.router.navigate 不起作用

问题描述 投票:0回答:1

我面临一个奇怪的问题。

我有一个注销功能,如果 401 响应我点击的任何 API,该功能就会被触发。

功能如下:

logout() {
    debugger
    this.refreshTokenInProgress = false;
    PreAngular.clearAll();
    localStorage.clear();
    if (window.location.href.indexOf("/public/login") == -1) {
      this.router.navigate(["/public/login"]);
    }
  }

按以下方式调用此注销函数:

  sendRequest(
    request: HttpRequest<any>,
    next: HttpHandler,
    isCacheable: Boolean,
  ) {
    return next.handle(request).pipe(
      catchError((error) => {
        if (error.status === 401 || (error.error != null && error.error.code == "0101")) {
          this.logout();
          //
          return throwError(error);
        }
      }),
    );

在我的应用程序场景中,我强制从数据库中注销某人,并且如果他们尝试访问任何 API,他们就会被注销,他们会收到 401 响应。我希望当他们收到 401 时,他们应该被注销。而不是注销,而是在强制注销后我尝试路由的页面的打字稿中抛出错误。例如,对于一个页面,它会在以下用 NgOnit 编写的函数上抛出错误。

ngOnInit() {
    this.activeUserListingForm = this.createFormGroup();
    this.isLogin = PreAngular.getUserInfo();
    this.manager = "manager";

    this.loadData();
  }
loadData() {
    this.formInProgress = true;
    this.usersService
      .getActiveUsersListing(
        this.skip / this.pageSize,
        this.pageSize,
        this.buildSearchParameters(),
        this.activeUserListingForm?.controls["searchInput"].value,
        this.dynamicColumns,
        this.sort,
      )
      .subscribe(
        (response) => {
          this.gridData = response;
          console.log(this.gridData);
          this.formInProgress = false;
          if (!response) this.toastr.error("Error", "No Record Found");
        },
        (err) => {
          console.log("Here in error" + err);
          this.toastr.error("Something went wrong");
        },
      );
  }

控制台在 errorTypeError: this.router.navigate is not a function 中打印 Here

函数loaddata位于xyz.ts中,它是我在强制注销后打开的页面的ts,上面是oauth.ts。

我尝试应用调试器,代码在注销的所有上面运行,并在 this.router.navigate 行上抛出错误。

任何指导和前进的方向都意义重大。谢谢

编辑: 该错误出现在我试图访问的 API 文件中。上面的 loaddata 代码是一个示例 API。所以它不像错误总是在同一个文件中抛出。这取决于调用哪个 api。

angular typescript api frontend
1个回答
0
投票

您需要将路由器作为参数传递给函数,如下所示

  logout(router: Router) {
    debugger
    this.refreshTokenInProgress = false;
    PreAngular.clearAll();
    localStorage.clear();
    if (window.location.href.indexOf("/public/login") == -1) {
      router.navigate(["/public/login"]);
    }
  }

然后你可以注入路由器,如果你使用像这样的功能防护

sendRequest(
    request: HttpRequest<any>,
    next: HttpHandler,
    isCacheable: Boolean,
  ) {
    return next.handle(request).pipe(
      catchError((error) => {
        if (error.status === 401 || (error.error != null && error.error.code == "0101")) {
          this.logout(this.router);
          //
          return throwError(error);
        }
      }),
    );

如果您的路由器未定义。如果您使用功能守卫,则只能在拦截器函数或类的顶层完成

    const router = inject(Router); // works only for functional interceptor

如果您使用的是普通课程

constructor(
...
private router: Router,
...
) {}
© www.soinside.com 2019 - 2024. All rights reserved.