Skip to content

Commit

Permalink
refactor: injectRouteFragment
Browse files Browse the repository at this point in the history
  • Loading branch information
Dafnik committed Jul 15, 2024
1 parent cdb3352 commit 0c240e0
Showing 1 changed file with 24 additions and 16 deletions.
40 changes: 24 additions & 16 deletions libs/ngxtension/inject-route-fragment/src/inject-route-fragment.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,25 @@
import { inject, type Injector, type Signal } from '@angular/core';
import { inject, type Signal } from '@angular/core';
import { toSignal } from '@angular/core/rxjs-interop';
import { ActivatedRoute } from '@angular/router';
import { assertInjector } from 'ngxtension/assert-injector';
import {
DefaultValueOptions,
InjectorOptions,
TransformOptions,
} from 'ngxtension/shared';
import { map } from 'rxjs';

export interface InjectRouteFragmentOptions<T = unknown> {
/**
* A transformation function.
*
* @param fragment - The fragment value to transform.
* @returns The transformed value.
*/
transform?: (fragment: string | null) => T;

/**
* The optional "custom" Injector. If this is not provided, will be retrieved from the current injection context
*/
injector?: Injector;
}
/**
* The `InjectRouteFragmentOptions` type defines options for configuring the behavior of the `injectRouteFragment` function.
*
* @template T - The expected type of the read value.
*/
export type InjectRouteFragmentOptions<T = unknown> = TransformOptions<
T,
string | null
> &
InjectorOptions &
DefaultValueOptions<T>;

/**
* The `injectRouteFragment` function allows you to access and transform url fragment from the current route.
Expand All @@ -43,7 +45,13 @@ export function injectRouteFragment<T>(
const route = inject(ActivatedRoute);
const initialRouteFragment = route.snapshot.fragment;
const getFragment = (fragment: string | null) => {
if (options?.transform) return options.transform(fragment);
if (fragment === null && options?.defaultValue) {
return options.defaultValue;
}
if (options?.transform) {
return options.transform(fragment);
}

return fragment;
};
const fragment$ = route.fragment.pipe(map(getFragment));
Expand Down

0 comments on commit 0c240e0

Please sign in to comment.