2

I am getting confused how to pass interface as parameter and set to http get ,post as globally

I written all http post, get, put, delete functions globally

  public get_api(path: string, Interface) {
    return this.http.get<Interface>(API_ENDPOINT + path);
  }

Now I want to pass interface from another .ts file

  this.http_global.get_api('user',Interface).subscribe(.....=>);

Can anyone helps !!!

Thanks In advance!!!!

1 Answer 1

6

You need to pass it as a generic type parameter, just as http.get does:

public get_api<T>(path: string) {
  return this.http.get<T>(API_ENDPOINT + path);
}

this.http_global.get_api<Interface>('user').subscribe(.....=>);

If there is a clear relation between the string passed in an the result type, you might consider adding some overloads so the user doesn't have to specify the type all the type:

public get_api(path: 'user'): Observable<User>
public get_api<T>(path: string) : Observable<T>
public get_api<T>(path: string) : Observable<T> {
  return this.http.get<T>(API_ENDPOINT + path);
}

this.http_global.get_api<Interface>('other').subscribe(.....=>);
this.http_global.get_api<('user').subscribe(.....=>); // Observable<User>
Sign up to request clarification or add additional context in comments.

1 Comment

@user3556287 don't forget to accept the answer if it was useful :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.