Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
106
rated 0 times [  112] [ 6]  / answers: 1 / hits: 20925  / 6 Years ago, tue, april 3, 2018, 12:00:00

I currently have a service that do a HTTP request to an API to fetch data. There are some logic that I want to do to the observable from within the service, but I still want to also subscribe to the Observable in my Component so that I can return any errors to the Component and to the user.



Currently I do:





// service.ts
getData(): Observable<any> {
return this.http.get(url).pipe(catchError(this.handleError)
}

// component.ts
ngOnInit() {
this.service.getData().subscribe(res => {
// Do my logic that belong to the service.ts
// ...

// Do my logic that belongs in the component.ts
// ...
}, err => this.errors = err)
}


What I would like to do is to refactor this so that I handle the logic related to the subscription and the service.ts within the getData() method, and then return an Observable with the HTTP response and any errors to the Component so that I can continue doing things there.



What's the pattern to do this?


More From » angular

 Answers
15

I feel like multiple of the patterns and solutions posted is "ugly" or does not follow the Observable pattern (Like doing callbacks).


The cleanest, most "RxJS"-like solution I came up with was to wrap the service method's return value in a second Observable.


So the following:



// service.ts
getData(): Observable<any> {
return new Observable(subscriber => {
this.http.get(url)
.pipe(catchError(this.handleError)
.subscribe(res => {
// Do my service.ts logic.
// ...
subscriber.next(res)
subscriber.complete()
}, err => subscriber.error(err))
})
}

// component.ts
ngOnInit() {
this.service.getData().subscribe(res => {
// Do my component logic.
// ...
}, err => this.errors = err)
}

[#54782] Friday, March 30, 2018, 6 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
nora

Total Points: 248
Total Questions: 111
Total Answers: 97

Location: India
Member since Wed, Aug 4, 2021
3 Years ago
;