2

有没有办法在 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
}

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

4

2 回答 2

3

你可能想看看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
     } 
];
于 2020-12-04T09:35:11.160 回答
0

你可以title在你的routes

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;
  ...
}
于 2021-06-15T00:15:50.377 回答