有没有一种方法可以避免在每个服务中编写相同的代码。
我为不同的API端点提供了多种服务:
getLecturesData(orderBy?: string, orderDirection = 'asc', page = 1, pageSize = 10): Observable<LecturesData> {
let params = new HttpParams();
params = params.set('order_direction', orderDirection);
params = params.set('page', page.toString());
params = params.set('page_size', pageSize.toString());
if (orderBy) { params = params.set('order_by', orderBy); }
return this.http.get<LecturesData>('/api/lectures', {params});
}
getStudentsData(orderBy?: string, orderDirection = 'asc', page = 1, pageSize = 5): Observable<StudentsData> {
let params = new HttpParams();
params = params.set('order_direction', orderDirection);
params = params.set('page', page.toString());
params = params.set('page_size', pageSize.toString());
if (orderBy) { params = params.set('order_by', orderBy); }
return this.http.get<StudentsData>('/api/students', {params});
}
正如您所看到的,除了返回值的url
和type
之外,代码几乎相同。有可能把复制的部分放在一个单独的"东西"里吗?
我会为参数创建一个接口,并创建一个专用的泛型函数来发出请求。
export interface QueryOptions {
orderBy?: string;
orderDirection: string;
page: number;
pageSize: number;
}
getLecturesData(options: QueryOptions): Observable<LecturesData> {
return this.getData<StudentsData>('/api/lectures', options);
}
getStudentsData(options: QueryOptions): Observable<StudentsData> {
return this.getData<StudentsData>('/api/students', options);
}
private getData<T>(options: QueryOptions): Observable<T> {
const params: HttpParams = this.getOptionsParams(options);
return this.http.get<T>(url, {params});
}
private getOptionsParams(options: QueryOptions): HttpParams {
let params = new HttpParams();
params = params.set('order_direction', options.orderDirection || 'asc');
params = params.set('page', (page || 1).toString());
params = params.set('page_size', (pageSize || 10).toString());
if (orderBy) { params = params.set('order_by', orderBy); }
return params;
}