我在同一页面上使用一些查询字符串参数调用router.navigate
。在这种情况下,ngOnInit()
不会打电话。它是默认还是我需要添加其他内容?
你可以注入ActivatedRoute
并订阅params
constructor(route:ActivatedRoute) {
route.params.subscribe(val => {
// put the code from `ngOnInit` here
});
}
路由器仅在导航到不同路径时销毁并重新创建组件。如果仅更新路径参数或查询参数但路径相同,则不会销毁和重新创建组件。
强制重新创建组件的另一种方法是使用自定义重用策略。另见Angular2 router 2.0.0 not reloading components when same url loaded with different parameters?(似乎没有太多可用的信息,但如何实现它)
您可以在路由器上调整reuseStrategy。
constructor(private router: Router) {
// override the route reuse strategy
this.router.routeReuseStrategy.shouldReuseRoute = function() {
return false;
};
}
也许你真的需要重新加载页面?这是我的解决方案:我已经更改了@NgModule(在我的案例中,在app-routing.module.ts文件中):
@NgModule({
imports: [RouterModule.forRoot(routes, {onSameUrlNavigation: 'reload'})] })
在创建实例时,将调用NgOnInit
一次。对于相同的实例,NgOnInit
将不再被调用。为了调用它,有必要销毁创建的实例。
此问题可能来自于您未使用ngOnDestroy终止订阅的事实。这是如何完成的。
import { Subscription } from 'rxjs/Subscription';
import { Component, OnDestroy, OnInit } from '@angular/core';
export class DisplayComponent implements OnInit, OnDestroy {
myVariable: Subscription;
this.myVariable = this.rmanagerService.getRPDoc(books[i].books.id).subscribe(value => {});
ngOnDestroy() {
this.myVariable.unsubscribe();
}
考虑将ngOnInit中的代码移动到ngAfterViewInit中。后者似乎在路由器导航上被调用,在这种情况下应该会帮助你。
当您想要路由器在同一页面上导航并想要调用ngOnInit()时,您也可以这样做,例如,
this.router.navigate(['category / list',category])。then(()=> window.location.reload());