- Auto Inject
HttpClientto extended classHttpHelperwithout injecting in base classLoginService
I've many services which are having HTTP API calls. I have created a common HTTP Class that instantiates httpClient and some other helper variables and functions that services can directly use without repetitive instantiation.
login.service.ts
@Injectable()
export class LoginService extends HttpHelper{
constructor(private http: HttpClient,
private authService: AuthService,
private userManagementService: UserManagementService) {
super(this.http);
}
login(data: IAuthPayload): Observable<any> {
return this.http.post(this.apiUrl + '/users/login', data, this.getHttpOptions({
auth: false
}))
.pipe(
map((res: ILoginResponse) => {
AuthService.setToken(res.data.token);
this.userManagementService.setUserData(res.data.user);
this.authService.setAuthState({ is_logged_in: true });
})
);
}
}
http.helper.ts
export class HttpHelper {
protected apiUrl = '';
constructor(private http: HttpClient) {
this.apiUrl = ENVIRONMENT.API_ENDPOINT;
}
protected getHttpOptions(options?: CustomHttpHeaderOptions) {
// function Definition
}
// Many More members here
}
LoginServiceextends theHttpHelperandhttpClientinstantiation must be in theHttpHelperand not in any service. e.g.LoginService.- is that possible if we just extend the
HttpHelperand not injecthttpClientinto theLoginService.httpClientshould auto inject inhttpHelperand we will usehttpClientinLoginServicewithout injecting it into service and use directlyhttpHelperhttpClientinstance.