Angular Router navigate 和 reload 需要渲染组件一次但是渲染了两次

Angular Router navigate and reload need to render the component once but renders twice

我遇到特殊情况,需要重定向到 url 并重新加载。

我在路由器上使用这个方法:

this.router.navigateByUrl('login');
this.reload();

其中 this.reload() 是在 angular 区域外运行以强制重新加载页面的函数。我需要强制重新加载,因为我无法控制来自服务器的某些资产。

重载代码为:

public reload(): any {
    return this.zone.runOutsideAngular(() => {
        location.reload()
    });
}

问题是:

我一开始被导航到登录页面,然后页面被重新加载,这是默认行为。

要求输出:

只需导航而不渲染组件并重新加载,就像当我们遇到一些未授权的 url 我们被重定向到大多数网站的登录页面。

如果有人有兴趣做我正在做的事情,我已经解决了这个问题,方法是先转到 url 然后重新加载页面。

首先导入Location:

import { Location } from "@angular/common";

然后使用 go() 导航到您期望的 url。

this.location.go('login');

然后使用reload方法重新加载浏览器。

this.reload();

其中重新加载函数是:

public reload(): any {
    return this.zone.runOutsideAngular(() => {
        location.reload()
    });
}

注:

此方法仅适用于导航和重新加载而不向用户显示两次页面加载的情况。