我有一個菜單欄包含從express api加載的菜單,並且每個菜單都被引用到具有別名的頁面,這將是該頁面的url 我正在嘗試加載頁面當我點擊菜單,它這樣做,但我刷新頁面 這是我的菜單代碼Angular 2 ngOnInit不會在routerlink更改時調用
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 {
}
Home of application with the menu bar
順便說。路線順序很重要。你的應用中沒有任何路由通過「PageComponent」?例如,甚至家庭,菜單或聯繫人。我的意思是更具體的路線應該位於頂部,下面更寬泛。 –
我無法從您的問題中得出哪些代碼/ html剪切屬於哪個組件,也不知道'menu.page.alias'可能返回哪個路由名稱。 –
Sharikov Vladislav,是的,所有菜單的URL從別名傳遞給PageComponent,我的問題是當我點擊菜單列表時頁面內容沒有加載,但當我刷新頁面時,它的加載 –