Angular inject() usage
We can use inject() function to inject the service in the angular project instead of inject in the constructor().
When we have a service that rely on an abstract interface, we need a a little tricky to have this inject() work. for example, we have a a interface:
export interface IStorageService {
get(key: string): any;
set(key: string, value: any): any;
remove(key: string): void;
}
@Injectable({
providedIn: 'root',
})
export class StorageService implements IStorageService {
get(key: string): any {
return localStorage.getItem(key);
}
set(key: string, value: any): any {
localStorage.setItem(key, value);
}
remove(key: string): any {
localStorage.removeItem(key);
}
}
if we use
private storage = inject(StorageService);
to inject the servcie, it wil raise the error like:
No suitable injection token for parameter 'storage' of class 'JwtInterceptor'. Consider using the @Inject decorator to specify an injection token
the solution is we need to define a InjectToken
export const STORAGE_SERVICE = new InjectionToken<IStorageService>(
'STORAGE_SERVICE'
);
then in the component, we can inject the servcie:
private storage = inject(STORAGE_SERVICE);