0
  • Auto Inject HttpClient to extended class HttpHelper without injecting in base class LoginService

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 
}
  • LoginService extends the HttpHelper and httpClient instantiation must be in the HttpHelper and not in any service. e.g. LoginService.
  • is that possible if we just extend the HttpHelper and not inject httpClient into the LoginService. httpClient should auto inject in httpHelper and we will use httpClient in LoginService without injecting it into service and use directly httpHelper httpClient instance.
Yash Majithiya
  • 861
  • 1
  • 8
  • 20

1 Answers1

1

You Can easily create your injectable class with Angular Injector:

import {Injector} from '@angular/core';

/**
 * Allows for retrieving singletons using `AppInjector.get(MyService)` (whereas
 * `ReflectiveInjector.resolveAndCreate(MyService)` would create a new instance
 * of the service).
 */
export let AppInjector: Injector;

/**
 * Helper to set the exported {@link AppInjector}, needed as ES6 modules export
 * immutable bindings (see http://2ality.com/2015/07/es6-module-exports.html) for 
 * which trying to make changes after using `import {AppInjector}` would throw:
 * "TS2539: Cannot assign to 'AppInjector' because it is not a variable".
 */
export function setAppInjector(injector: Injector) {
    if (AppInjector) {
        // Should not happen
        console.error('Programming error: AppInjector was already set');
    }
    else {
        AppInjector = injector;
    }
}

And Use it this way:

import {AppInjector} from './app-injector';
const myService = AppInjector.get(MyService);

See this answer

Masoud Bimmar
  • 6,941
  • 4
  • 30
  • 33