Angular 角度路由器在使用自定义ngDoBootstrap和createCustomElement时忽略URL
当我使用自定义的Angular 角度路由器在使用自定义ngDoBootstrap和createCustomElement时忽略URL,angular,typescript,angular8,angular-router,custom-element,Angular,Typescript,Angular8,Angular Router,Custom Element,当我使用自定义的ngDoBootstrap函数而不是默认的bootstrap:[AppComponent]如下: @NgModule({ imports: [ BrowserModule, FormsModule, AppRoutingModule ], declarations: [ AppComponent, HelloComponent ], exports: [ AppComponent ], entryComponents: [ AppComponent ],
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中的任何更改,仅在我单击时起作用(需要下载并在本地运行,因为stackblitz使用的是typescript版本)
如何使用自定义应用程序模块引导使路由工作?我通过以下方法使其工作
据我所知,angular元素并不真正支持内部应用程序路由(请参见此)和此open
解决方案是在位置改变时手动指示路由器导航到内部路由
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);
});
}
以下是工作原理对于自定义元素,必须手动调用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();
}
}
我添加了一个polyfill,使其在stackblitz上工作:。“初始路线/未装载”是什么意思?它重定向到中定义的#/hello
routing@David:首先,由于路由配置的原因,它应该自动重定向到#/hello。没有。第二,如果直接打开,则不会激活路由。此外,对URL的任何更改都将被忽略。只需直接点击链接,我想我昨天有点困惑,我可以发誓它是按预期工作!但我今天又检查了一遍,结果确实不起作用。我发布了一个答案,希望能帮助你,它不会造成内存泄漏吗?在我的例子中,my app自定义元素被动态添加,并从DOM中删除。当元素从dom中删除时,该应用程序被构建并用作webcomponentUnsubscribe from location?感谢您的帮助。我想router.initialNavigation()就是我要找的