injectRouteData
Created by Krzysztof Kachniarz
injectRouteData is a helper function that allows us to inject data from the current route as a signal.
Having route data as a signal helps in a modern angular signals based architecture.
import { injectRouteData } from 'ngxtension/inject-route-data';Usage
injectRouteData when is called, returns a signal with the current route data.
@Component({ standalone: true, template: '<div>{{routeData() | json}}</div>',})class TestComponent { routeData = injectRouteData();}Or, if we want to transform the data, we can pass a function to injectRouteData.
@Component()class TestComponent { routeDataKeys = injectRouteData((data) => Object.keys(data)); // returns a signal with the keys of the route data object}Specific value
If we want to get the value for a specific key, we can pass the name of the object key to injectRouteData.
@Component({ template: ` <div>{{ details().name }}</div> <div>{{ details().description }}</div> `,})class TestComponent { details: Signal<unknown> = injectRouteData('details'); // returns a signal with the value of the details key in route data object}You can also pass a custom injector or defaultValue.
@Component()class TestComponent implements OnInit { injector = inject(Injector);
detailsWithDefaultValue: Signal<string> = injectRouteData('details', { defaultValue: 'abc', });
ngOnInit() { const detailsWithCustomInjector: Signal<boolean> = injectRouteData( 'details', { injector: this.injector, }, ); }}