【问题标题】:Angular Router ignores URL, when using custom ngDoBootstrap and createCustomElementAngular 路由器在使用自定义 ngDoBootstrap 和 createCustomElement 时忽略 URL
【发布时间】:2020-03-05 14:55:17
【问题描述】:

WHEN 我使用自定义ngDoBootstrap 函数而不是默认bootstrap: [AppComponent],如下所示:

@NgModule({
  imports:      [ BrowserModule, FormsModule, AppRoutingModule ],
  declarations: [ AppComponent, HelloComponent ],
  exports: [ AppComponent ],
  entryComponents: [ AppComponent ],
  // bootstrap: [AppComponent],
})
export class AppModule {
  constructor(private injector: Injector) {
  }

  public ngDoBootstrap(): any {
    const appElement = createCustomElement(AppComponent, { injector: this.injector });
    customElements.define('my-app', appElement);
  }
}

那么 应用程序路由已损坏。

它会忽略 URL 中的任何更改,并且仅在我单击 <a [routerLink]='...'> 时才有效。初始路由 / 也未加载。

这一定是由自定义引导机制引起的,因为当我取消注释 bootstrap: [AppComponent] 时,一切正常。

完整代码在这里:stackblitz sample(由于 stackblitz 使用 typescript 版本,需要下载并在本地运行)

如何使路由与自定义应用模块引导一起工作?

【问题讨论】:

  • 我添加了一个 polyfill 以使其在 stackblitz 上工作:stackblitz.com/edit/angular-customelements-routing-ts7dyc。 “初始路线/未加载”是什么意思?它重定向到#/hello,如路由中所定义的
  • @David:首先,由于路由配置,它应该自动重定向到#/hello。它没有。第二,如果你直接打开#/hello,那么路由是没有激活的。此外,对 URL 的任何更改都将被忽略。只有直接点击链接才有效
  • 我想我昨天很困惑,我可以发誓它按预期工作!但是我今天再次检查,确实没有用。我发布了一个希望对您有所帮助的答案

标签: angular typescript angular8 angular-router custom-element


【解决方案1】:

我设法通过关注this tutorial 使其工作。

据我了解,角度元素并不真正支持内部应用程序路由(请参阅此SO post)和此开放github issue

解决方法是在位置发生变化时手动指示路由器导航到内部路由

export class AppModule {
  constructor(private injector: Injector, private router: Router,
    private location: Location) {
    const appElement = createCustomElement(AppComponent, { injector: this.injector });
   customElements.define('my-app', appElement);

    /**Add the lines below to your code**/
   //init router with starting path
    this.router.navigateByUrl(this.location.path(true));

    //on every route change tell router to navigate to defined route
    this.location.subscribe(data => {
      this.router.navigateByUrl(data.url);
    });

}

这是工作的stackblitz example

【讨论】:

  • 不会造成内存泄漏吗?在我的例子中,my-app 自定义元素是动态添加的,或者是从 DOM 中删除的。该应用程序已构建并用作 web 组件
  • 从 dom 中删除元素时取消订阅位置?
  • 感谢您的帮助。我认为 router.initialNavigation() 是我正在寻找的
【解决方案2】:

如果是自定义元素,必须手动调用 router.initialNavigation:

export class AppModule {
  constructor(private injector: Injector, private router: Router,
    private location: Location) {
    const appElement = createCustomElement(AppComponent, { injector: this.injector });
    customElements.define('my-app', appElement);


  public ngDoBootstrap(): void {
    // workaround for bug - initial route not loaded: https://github.com/angular/angular/issues/23740
    this.router.initialNavigation();
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-04-11
    • 1970-01-01
    • 1970-01-01
    • 2014-04-23
    • 2013-06-28
    相关资源
    最近更新 更多