在静态路由中使用resolve属性来解决数据解析问题。以下是一个示例:
app-routing.module.ts
import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { HomeComponent } from './home/home.component';
import { AboutComponent } from './about/about.component';
import { ContactComponent } from './contact/contact.component';
import { NotFoundComponent } from './not-found/not-found.component';
const routes: Routes = [
{
path: '',
component: HomeComponent
},
{
path: 'about',
component: AboutComponent,
resolve: {
data: AboutResolver // resolve data before navigating to AboutComponent
}
},
{
path: 'contact',
component: ContactComponent,
resolve: {
data: ContactResolver // resolve data before navigating to ContactComponent
}
},
{
path: '**',
component: NotFoundComponent
}
];
@NgModule({
imports: [RouterModule.forRoot(routes)],
exports: [RouterModule]
})
export class AppRoutingModule { }
about.resolver.ts
import { Injectable } from '@angular/core';
import { Resolve } from '@angular/router';
import { Observable } from 'rxjs';
import { AboutService } from './about.service';
@Injectable({
providedIn: 'root'
})
export class AboutResolver implements Resolve {
constructor(private aboutService: AboutService) { }
resolve(): Observable {
return this.aboutService.getData();
}
}
contact.resolver.ts
import { Injectable } from '@angular/core';
import { Resolve } from '@angular/router';
import { Observable } from 'rxjs';
import { ContactService } from './contact.service';
@Injectable({
providedIn: 'root'
})
export class ContactResolver implements Resolve {
constructor(private contactService: ContactService) { }
resolve(): Observable {
return this.contactService.getData();
}
}
关键点: