I have this api global service for http request:
network.service:
import { Injectable } from '@angular/core';
import { HttpHeaders, HttpClient, HttpParams } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { catchError } from 'rxjs/operators';
@Injectable({
providedIn: 'root'
})
export class NetworkService {
constructor(
private http: HttpClient
) { }
private formatErrors(error: any) {
return throwError(error.error);
}
get(environment: string, path: string, params: HttpParams = new HttpParams()): Observable<any> {
return this.http.get(`${environment}${path}`, { params })
.pipe(catchError(this.formatErrors));
}
put(environment: string, path: string, body: object = {}): Observable<any> {
return this.http.put(
`${environment}${path}`,
JSON.stringify(body)
).pipe(catchError(this.formatErrors));
}
post(environment: string, path: string, body: object = {}): Observable<any> {
return this.http.post(
`${environment}${path}`,
JSON.stringify(body)
).pipe(catchError(this.formatErrors));
}
delete(environment: string, path: string): Observable<any> {
return this.http.delete(
`${environment}${path}`
).pipe(catchError(this.formatErrors));
}
}
I try to make the function accept model when i call the service in other place like this:
import { NetworkService } from '@globalCore/services/network.service';
import { Flows } from '@modules/home/models/flows.model';
@Injectable({
providedIn: 'root'
})
export class ApiService {
private REPORTS_API = 'reports';
private USER_API = 'user';
constructor(private network: NetworkService) {
this.baseUrl = environment.apiUrl;
}
getFlows(userID: number) {
return this.network.get<Flows>(this.baseUrl, `${this.REPORTS_API}/${this.USER_API}/${userID}`);
}
But i get error on the model
Expected 0 type arguments, but got 1.ts(2558)
But if i put the model on the global newtwork.service its work but i need a way to do this in other places when i call to function from other places and not in the global. thanks
this.network.get<Flows>(...). Make it generic, just as HttpClient.get<>() is.${environment}${path}, { params }) .pipe(catchError(this.formatErrors)); } And then you don't need to define type of your get() call.