我有一个DataService,它通过不同的api调用返回一个可观察的对象,我需要重用以下代码块并在每个http请求中调用。
export class DataService {
constructor(
private http: HttpClient, ) {}
fetchWind(): Observable<ModelClass> {
return this.http
.get<StaticDataElements>(Wind_REQUEST_URL)
.pipe(
tap(
response => response,
error => this.handleError(error, 'Service_Failure')
)
);
}
fetchEmission(): Observable<ModelClass> {
return this.http
.get<ModelClass>(Emission_REQUEST_URL)
.pipe(
tap(
response => response,
error => this.handleError(error, 'Service_Failure')
)
);
}
fetchSolar(): Observable<ModelClass> {
return this.http
.get<ModelClass>(Solar_REQUEST_URL)
.pipe(
tap(
response => response,
error => this.handleError(error, 'Service_Failure')
)
);
}
这是每个服务调用的重复代码,需要编写一个函数来传递请求url并获取响应和错误。在这里,太阳能,风能,发射器在三个http调用中重复了相同的代码,除了url,响应和错误
return this.http
.get<ModelClass>(Solar_REQUEST_URL)
.pipe(
tap(
response => response,
error => this.handleError(error, 'Service_Failure')
)
);
答案 0 :(得分:1)
如果您要避免重复此行:
.pipe(
tap(
response => response,
error => this.handleError(error, 'Service_Failure')
)
);
然后,编写这样的方法:
getRespons<T>(url:string){
return this.http
.get<T>(url)
.pipe(
tap(
response => response,
error => this.handleError(error, 'Service_Failure')
)
);
}
并以这种方式使用它:
fetchSolar(): Observable<ModelClass> {
return this.getRespons<ModelClass>(Solar_REQUEST_URL);
}
答案 1 :(得分:0)
减少重复代码的一种策略是简单地公开可订阅的可观察对象。
在数据服务中,您可以添加以下更改:
export class DataService {
solarData$: Observable<ModelClass>;
constructor(
private http: HttpClient, ) {
this.solarData$ = this.fetchSolar();
}
fetchWind(): Observable<ModelClass> {
return this.http
.get<StaticDataElements>(Wind_REQUEST_URL)
.pipe(
tap(
response => response,
error => this.handleError(error, 'Service_Failure')
)
);
}
fetchEmission(): Observable<ModelClass> {
return this.http
.get<ModelClass>(Emission_REQUEST_URL)
.pipe(
tap(
response => response,
error => this.handleError(error, 'Service_Failure')
)
);
}
fetchSolar(): Observable<ModelClass> {
return this.http
.get<ModelClass>(Solar_REQUEST_URL)
.pipe(
tap(
response => response,
error => this.handleError(error, 'Service_Failure')
)
);
}
然后在每个组件中
。export class MyComponent implements <whatever> {
constructor(private dataService: DataService) {}
//in some method
foo() {
componentData$ = this.dataService.solarData$; // or subscribe and stuff
}
}