【问题标题】:Reset Angular router state in webcomponent (angular elements)在 webcomponent 中重置 Angular 路由器状态(角度元素)
【发布时间】:2022-06-16 22:02:24
【问题描述】:

我有一个简单的微前端场景,它在容器 webapp 中加载和嵌入一个 angular 13 webcomponent(使用 angular 元素创建)。 基本上,路由工作正常。离开路由时,ng Web 组件会得到一个ngOnDestroy,并且不再是 DOM 的一部分。

但是,如果我回到这条路线,角度 web 组件会显示最后一个活动路线(似乎有一些状态),它不反映 URL 浏览器位置。如果我手动重新加载浏览器 - 结果很好。 离开路线时,角度网络组件似乎没有正确断开/销毁。有什么改变可以强迫这个吗? 这样在重新进入路由时,一切看起来就像是第一次加载(类似于浏览器刷新)。

【问题讨论】:

    标签: angular web-component angular-elements


    【解决方案1】:

    我也在为同样的行为而苦苦挣扎,为此我找到了两种解决方法。

    1. 如果未设置 location.path(),则重定向到主页
    export class AppComponent {
        constructor (private router: Router, private location: Location) {
            this.router.initialNavigation()
            if (!this.location.path()) {
              this.router.navigate(['']).then()
            }
          }
        }
    
    1. 创建 JumpOff 页面,您将从该页面导航到其他 Web 组件。当您返回此 JumpOff 页面/组件时,在导航到“主页”时清除状态
    constructor (private readonly router: Router) {
        if (navigation_from_external_webcomponent) {
            this.router.navigate([''], { replaceUrl: true }).then()
        }
    }
    

    replaceUrl 应该清除路由器的状态。如果第二个选项不起作用,请尝试添加:

        this.location.replaceState('')
    

    (location 是 Location 类,不是 LocationStrategy)

    第二个选项的另一个问题是我多次调用这个组件,所以我需要用 setTimeout 包装导航:

        setTimeout(() => {
            this.router.navigate([''], { replaceUrl: true }).then()
        })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 2013-12-24
      • 2018-05-10
      相关资源
      最近更新 更多