javascript - Angular 2 - 组件内的路由
昨天我问了一个关于 Angular 2 路由的具体问题,答案让我很满意:Angular 2 — 在不重新加载那些页面共有的组件的情况下浏览网页。但是当我回去检查这些问题时,我又遇到了问题。这里是应用的新版本:http://ivan-khludov.com/。如果我想让私有部分的页面有一个共享组件(在我的例子中是一个计数器),在该部分内导航时不重新加载它,同时在不同页面显示不同的组件——例如 private/dashboard 显示 dashboard 组件,private/inbox 显示 inbox 组件——这是可能的吗?在不重载计数器且不在内存中存储计数器的最后值的情况下可以实现吗?这是应用的入口点和根模块:
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HttpModule } from '@angular/http';
import { RouterModule } from '@angular/router';
import { BrowserModule } from '@angular/platform-browser';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { ROUTES } from './routes';
import { AppWrapper } from './components/app-wrapper';
import { PublicSection } from './components/public';
import { PrivateSection } from './components/private';
import { Counter } from './components/counter';
import { Dashboard } from './components/private/dashboard';
import { Inbox } from './components/private/inbox';
@NgModule({
imports: [
BrowserModule,
CommonModule,
HttpModule,
RouterModule.forRoot(ROUTES)
],
declarations: [
AppWrapper,
PublicSection,
PrivateSection,
Counter,
Dashboard,
Inbox
],
providers: [
],
bootstrap: [
AppWrapper
]
})
class RootModule {}
platformBrowserDynamic().bootstrapModule(RootModule);
路由:
import { Routes } from '@angular/router';
import { AppWrapper } from '../components/app-wrapper';
import { PublicSection } from '../components/public';
import { PrivateSection } from '../components/private';
export const ROUTES: Routes = [
{
path: '',
redirectTo: '/public/1',
pathMatch: 'full'
},
{
path: 'section-1',
redirectTo: '/public/1',
pathMatch: 'full'
},
{
path: 'public/:page',
component: PublicSection
},
{
path: 'private',
redirectTo: '/private/dashboard',
pathMatch: 'full'
},
{
path: 'private/:page',
component: PrivateSection
}
];
私有部分组件:
import { Component } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'private',
template: `
<h2>Private section — {{page}}</h2>
<counter></counter>
<dashboard></dashboard>
<inbox></inbox>
`
})
export class PrivateSection {
private page: string;
private sub: any;
constructor(
private route: ActivatedRoute
) {
}
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
this.page = params['page'];
});
}
ngOnDestroy() {
this.sub.unsubscribe();
}
}
仪表板组件:
import { Component } from '@angular/core';
@Component({
selector: 'dashboard',
template: `
<div>dashboard text: lorem ipsum</div>
`
})
export class Dashboard {
}
收件箱组件:
import { Component } from '@angular/core';
@Component({
selector: 'inbox',
template: `
<div>inbox text: dolor sit amet</div>
`
})
export class Inbox {
}
提前感谢您的回答。