Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Type of function should be dynamic

For each component I create a service which is more or less the same.

E.g.

save(values: any): Observable<Register> {
  return this.httpClient.put<Register>(environment.apiBaseUrl + 'register', values);
}

Instead of that, I want a general service that I can use for all components. Somehow like this:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

save(values: any, path: string): Observable<Register> {
  return this.httpClient.put<Register>(environment.apiBaseUrl + path, values);
}

Then I could use this.myService.save(myObject, 'my-path'). But what about the type Register? This time I want the type to be Login.

Is there a way I could tell the function what type it should be?

>Solution :

Yes, you can make the Register type generic:

function save<T>(values: any, path: string): Observable<T> {
  return this.httpClient.put<T>(environment.apiBaseUrl + path, values);
}

this is then called with

const observable = save<Register>(values, 'register');
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading