0

I need to create some angular services on the fly. I cannot wrap my head around how to work with DI and the http service. Please help!

import { HttpClient } from '@angular/common/http';

export class BaseService {
  constructor(private http: HttpClient) {}

  get() {
    return this.http.get('/endpoint');
  }
}

let service = new BaseService(HttpClient);
// doesn't work :(
benc
  • 1,978
  • 3
  • 15
  • 22
  • Does this answer your question? [How to instantiate an Angular HttpClient?](https://stackoverflow.com/questions/48372116/how-to-instantiate-an-angular-httpclient) – Heretic Monkey Mar 31 '20 at 17:16
  • Might want to check this out... https://stackoverflow.com/questions/42461852/inject-a-service-manually – Jason Goemaat Mar 31 '20 at 17:37

1 Answers1

0

Add between your import statement and your BaseService class declaration:

@Injectable({
  providedIn: 'root'
})

Then, in the class you want to use this BaseService in:

export class MyOtherClass {
    constructor(private baseClass: BaseClass) { }

    someMethod(): string{
        return baseClass.get();
    }
}

When you use your BaseService in your new class, Angular DI will give you a new instance of your Http Client when it is creating the instance of your BaseService. With DI in the constructor you're saying "give me an instance of this class when this is created". Angular DI knows how to do this from the @Injectable registration.

dskinner
  • 81
  • 3