Reputation: 2543
I have a DataService which returns an observable with different api call, I need to reuse the below block and call in each http request.
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')
)
);
}
Here is the duplicate code for each service call need to write one function to pass the request url and get the response and error. Here solar, wind, emissiom have same code repeated in three http calls other than url, response, error
return this.http
.get<ModelClass>(Solar_REQUEST_URL)
.pipe(
tap(
response => response,
error => this.handleError(error, 'Service_Failure')
)
);
Upvotes: 0
Views: 812
Reputation: 5493
if you mean avoid repeating this lines:
.pipe(
tap(
response => response,
error => this.handleError(error, 'Service_Failure')
)
);
then, write a method like this:
getRespons<T>(url:string){
return this.http
.get<T>(url)
.pipe(
tap(
response => response,
error => this.handleError(error, 'Service_Failure')
)
);
}
and use it in this way:
fetchSolar(): Observable<ModelClass> {
return this.getRespons<ModelClass>(Solar_REQUEST_URL);
}
Upvotes: 1
Reputation: 4821
One strategy to reducing duplicate code is to simply expose an observable that can be subscribed to.
In your data service you can add the following changes:
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')
)
);
}
Then in each of your components.
export class MyComponent implements <whatever> {
constructor(private dataService: DataService) {}
//in some method
foo() {
componentData$ = this.dataService.solarData$; // or subscribe and stuff
}
}
Upvotes: 0