簡體   English   中英

Angular 2 ngOnInit 在 routerlink 更改時不會被調用

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

我有一個菜單欄,其中包含從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();
}

}

這是我的模板菜單

<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 -->

我認為問題出在我的頁面組件的 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);
        });
    }

}

這是我的頁面模板

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

這是我的應用路由代碼

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 {}

這是我的應用組件

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

})
export class AppComponent {

}

帶有菜單欄的應用程序主頁

以下是Gunter所談論的代碼示例:

  constructor(private route: ActivatedRoute) { }

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

此代碼監視參數的更改並執行箭頭函數內的任何代碼。

當只有路由器參數發生變化但路由的基礎保持不變時,Angular會重用該組件。 ngOnInit()僅在實例化組件后調用一次,但在路徑更改時不調用。

您可以注入路由器並訂閱它的事件或參數以獲得有關路由更改的通知。

好吧,感謝@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);
            });
        }
    }

對這一個

@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