简体   繁体   English

Angular 2 ngOnInit 在 routerlink 更改时不会被调用

[英]Angular 2 ngOnInit is not called when routerlink changes

i have a menu bar that contain a list of menus loaded from express api and every menu is referenced to a page that have an alias wich will be the URL of that page i am trying to load the page when i click to menu, it's done but only when i refresh the page this my menu code我有一个菜单栏,其中包含从express api加载的菜单列表,每个菜单都引用到一个具有别名的页面,该页面将是该页面的 URL 我正在尝试在单击菜单时加载该页面,它已完成但只有当我刷新页面时,这是我的菜单代码

export class MenuList implements OnInit {

menus:Menu[];
menu:Menu;
page:Page;

constructor(private router:Router,
            private menuService:MenuService) {
}

getMenus():void {
    this.menuService.getMenus()
        .subscribe(
            menus => this.menus = menus, //Bind to view
            err => {
                // Log errors if any
                console.log(err);
            }
        );
}

getPage(id):void {
    this.menuService.getPage(id)
        .subscribe(
            page => this.page = page, //Bind to view
            err => {
                // Log errors if any
                console.log(err);
            });
}

ngOnInit():void {
    this.getMenus();
}

} }

and this is my template menu这是我的模板菜单

<div class="container-fluid">
    <!-- Brand and toggle get grouped for better mobile display -->
    <div class="navbar-header">
        <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false">
            <span class="sr-only">Toggle navigation</span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
            <span class="icon-bar"></span>
        </button>
    </div>

    <!-- Collect the nav links, forms, and other content for toggling -->
    <div class="collapse navbar-collapse" id="navbar"  style="background-color: #97455f">
        <div class="navv">
            <ul *ngFor="let menu of menus">
                <li class="col-lg-1 col-md-1 col-xs-12 col-sm-12"><a [routerLink]="[menu.page.alias]">{{menu.title}}</a></li>


            </ul>
        </div>
    </div>

</div><!-- /.navbar-collapse -->

I think the problem is in the ngOnInit of my page component, it's not called我认为问题出在我的页面组件的 ngOnInit 中,它没有被调用

    @Component({
    selector: 'page',
    templateUrl: './page.component.html'
})
export class PageComponent implements OnInit {
    alias: string;
    page:Page;

    constructor(private router:Router,
                private route: ActivatedRoute,
                private pageService:PageService) {

        this.route.params.subscribe(
            (params : Params) => {
                this.alias = params["alias"];
                console.log(this.alias)
            }
        );
    }




    ngOnInit():void {
        debugger;
        this.pageService.getPage(this.alias).subscribe(page => {
            this.page = page;
            console.log(this.page);
        });
    }

}

and this is my page template这是我的页面模板

    <p *ngIf="page" [innerHTML]="page.content" ></p>

this is my app routing code这是我的应用路由代码

const routes: Routes = [
    { path: '', redirectTo: '/home', pathMatch: 'full' },
    { path: ':alias', component: PageComponent },
    { path: 'archived',  component: ArchivedComponent },
    { path: 'home',  component: HomeComponent },
    { path: 'menu',  component: MenuList },
    { path: 'detail/:id', component: ActualiteDetailComponent },
    { path: 'contact',  component: ContactComponent },

];

@NgModule({
    imports: [ RouterModule.forRoot(routes) ],
    exports: [ RouterModule ]
})
export class AppRoutingModule {}

this is my app component这是我的应用组件

@Component({
  selector: 'my-app',
  template: `
    <menu-list></menu-list>
    <hr>
`

})
export class AppComponent {

}

Home of application with the menu bar带有菜单栏的应用程序主页

Here is a code example of what Gunter is talking about: 以下是Gunter所谈论的代码示例:

  constructor(private route: ActivatedRoute) { }

  ngOnInit() {
     this.route.params.subscribe(
     params => {
        let id= +params['id'];
        this.getProduct(id);
     });
  }

This code watches for changes to the parameters and executes any code inside the arrow function. 此代码监视参数的更改并执行箭头函数内的任何代码。

When only a router parameter is changes but the base of the route stays the same, Angular reuses the component. 当只有路由器参数发生变化但路由的基础保持不变时,Angular会重用该组件。 ngOnInit() is only called once after a component is instantiated, but not when the route changes. ngOnInit()仅在实例化组件后调用一次,但在路径更改时不调用。

You can inject the router and subscribe to it's events or params to get notified about route changes. 您可以注入路由器并订阅它的事件或参数以获得有关路由更改的通知。

Well it fixed thanks to @Günter Zöchbauer and @DeborahK I changed the Page Component code from this 好吧,感谢@GünterZöchbauer和@DeborahK,我更改了此页面组件代码

@Component({
selector: 'page',
templateUrl: './page.component.html'
    })
    export class PageComponent implements OnInit {
        alias: string;
        page:Page;

        constructor(private router:Router,
                    private route: ActivatedRoute,
                    private pageService:PageService) {

            this.route.params.subscribe(
                (params : Params) => {
                    this.alias = params["alias"];
                    console.log(this.alias)
                }
            );
        }

    ngOnInit():void {
            debugger;
            this.pageService.getPage(this.alias).subscribe(page => {
                this.page = page;
                console.log(this.page);
            });
        }
    }

to this one 对这一个

@Component({
selector: 'page',
templateUrl: './page.component.html'
    })
    export class PageComponent implements OnInit {
        alias:string;
        page:Page;

        constructor(private router:Router,
                    private route:ActivatedRoute,
                    private pageService:PageService) {

            this.route.params.subscribe(
                (params:Params) => {
                    this.alias = params["alias"];
                    this.pageService.getPage(this.alias).subscribe(page => {
                        this.page = page;
                        console.log(this.page);
                    });
                    console.log(this.alias)
                }
            );
        }
         ngOnInit():void {
            this.pageService.getPage(this.alias).subscribe(page => {
                this.page = page;
                console.log(this.page);
            });
        }
    }
import { Router } from '@angular/router';
...
export class SettingViewComponent implements OnInit {

 constructor(
   private router: Router
 ) { }

 public ngOnInit(): void {
    this.router.routeReuseStrategy.shouldReuseRoute = () => false;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM