Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using service in app.routing.module Angular

Is there a way to inject and use a service in the route list in the Angular routing module in order to dynamically change route data?

Like so:

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
}

How could I achieve dynamic behavior, like setting a custom title, in routes array?

like image 441
dzenesiz Avatar asked Aug 09 '26 15:08

dzenesiz


1 Answers

You probably want to take a look at 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();
  }
}

in router

const routes: Routes = [
  { 
     path: 'about', 
     component: AboutComponent, 
     resolve: { // use `resolve`
       title: TitleResolver
     } 
];
like image 58
deerawan Avatar answered Aug 12 '26 08:08

deerawan



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!