Currently utilizing angular 4 and angular cli for my project development. I have created some classes that serve as the base for my components! However, as the constructors of these classes grow during development, I find myself in a phase where I need to allow others to use them without requiring knowledge of their constructors!
After following Petr's suggestion in dependency injection, I attempted to implement it. However, I had to make certain adjustments due to compiler errors, which I assume are a result of differences between angular 4 and angular 5!
Below is the code snippet:
Service Locator:
import {ReflectiveInjector} from "@angular/core";
export class ServiceLocator {
static injector: ReflectiveInjector;
}
Module importing the serviceLocator:
ServiceLocator.injector = ReflectiveInjector.resolveAndCreate(
Object.keys(services).map(key => ({
provide: services[key].provide,
useClass: services[key].provide,
deps: services[key].deps
}))
);
serviceList:
import {SysFwDatesService} from '../sysDates/sysFwDates.service';
import {MatSnackBar} from '@angular/material';
import {SysFwFormSpecBuilder} from '../uiValidation/SysFwFormSpecBuilder';
import {SysFwHttpApi} from '../http/SysFwHttpApi';
export const services: {[key: string]: {provide: any, deps: any[], useClass?: any}} = {
'SysFwDatesService': {
provide: SysFwDatesService,
deps: []
},
'MatSnackBar': {
provide: MatSnackBar,
deps: []
},
'SysFwFormSpecBuilder': {
provide: SysFwFormSpecBuilder,
deps: []
},
'SysFwHttpApi': {
provide: SysFwHttpApi,
deps: []
}
}
The implementation appears to be functioning properly, but it seems to have disregarded other providers and now expects all providers to be passed in this manner!
An error message I encountered reads:
No provider for HttpClient! (SysFwDatesService -> SysFwHttpApi -> HttpClient)
Should everything be included in the servicesList? Where am I going wrong?
Everything was functioning correctly before using the injector!
Appreciate your assistance!