I'm trying to create data service in Angular which will be universal to all CRUD HTTP requests. However, I want public functions to return typed Observable<T>. So I figured I'd pass a type into my service's constructor, store in in local variable and then each client object to instantiate this service class would supply 'type' it expects from service's return functions so that my post, put, patch, delete and get would return already typed Observable. Something like this:
export class DataService {
constructor(private http: HttpClient, private dataType: Type )
}
getAll(): Observable<dataType[]> {
return http.get<dataType[]>(...);
}
post(dataIn: dataType): Observable<dataType> {
return http.post<dataType>(...);
}
}
Can it be done?
this.dataType, not justdataType. If you just want to support interfaces you could makeDataServicegeneric, if you want to return actual instances of classes you'll have to implement that yourself.