【问题标题】:Using service in app.routing.module Angular在 app.routing.module Angular 中使用服务
【发布时间】:2020-12-04 09:28:24
【问题描述】:

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

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

【问题讨论】:

    标签: angular angular-routing angular-dependency-injection


    【解决方案1】:

    你可能想看看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
         } 
    ];
    

    【讨论】:

    • 太棒了!您能否也告诉我是否可以访问route.data.someCustomProperty 并使用它来解决?目前,resolve() 触发时它不存在。我在网上看过,但没有运气。
    • @dzenesiz 嗯,这似乎是不可能的。将该自定义属性存储在服务中,然后将其注入 TitleResolver 怎么样?
    • 我实际上设法传递了像data: { myData: 'whatever} 这样的数据,然后通过访问route.data.myData 在解析器中使用它。我还有一个问题,如果可以的话 - 我需要在组件中手动设置解析值,还是自动设置标题?我问是因为它似乎不会是自动的。
    【解决方案2】:

    您可以在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;
      ...
    }
    

    【讨论】:

      猜你喜欢
      • 2017-09-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      • 2019-03-31
      • 2016-10-10
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多