在 app.routing.module Angular 中使用服务

Using service in app.routing.module Angular

有没有办法在Angular路由模块的路由列表中注入并使用一个服务来动态改变路由数据?

像这样:

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { MyComponent } from './my/my.component';

const routes: Routes = [
  { path: 'about', component: AboutComponent, data: {title: myService.getTitle()}} // use it?
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule {
    constructor(private myService: SomeService) {} // inject it
}

如何在路由数组中实现动态行为,例如设置自定义标题?

你可能想看看 Resolve

@Injectable({ providedIn: 'root' })
export class TitleResolver implements Resolve<Hero> {
  constructor(private service: TitleService) {}

  resolve(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot
  ): Observable<any>|Promise<any>|any {
    return this.service.getTitle();
  }
}

在路由器中

const routes: Routes = [
  { 
     path: 'about', 
     component: AboutComponent, 
     resolve: { // use `resolve`
       title: TitleResolver
     } 
];

您可以在 routes

中访问 title
const routes = [
  { path: 'about', customData: myValue, component: AboutComponent, data: {title: myService.getTitle()}} // use it?
];

在任何组件或服务中:

@Injectable({
  providedIn: 'root'
})
export class MyService {
  constructor(private router: Router) { };
  ...
  this.router.config[0].data.title;
  ...
}