I have inherited an Angular project and there are some parts of the code to tidy up. One area in particular is a pattern I haven't seen and I don't understand the benefit or reason behind it and it has been used quite heavily throughout.
The pattern appears to be primarily used in conjunction with Http calls (i.e. this.http.get<any>...) within Service classes such that a method on the class will return a new Promise, and within that promise a call to this.http.get(url) is subscribed and then within the subscribe method the outer promise is resolved with the subscription value. Sometimes there is another Observable (e.g. BehaviourSubject) on the class which has a new value supplied as part of the inner .subscribe() body and I can see this value is used by components which import the service class.
Of note are other methods on the class which use the resolved promise as part of a Promise.all() chain to provide data resolving functionality or other functions.
As this is using the Angular HttpClient I don't think there are memory leaks happening here or lots of to be unsubscribed subscriptions although happy to hear feedback on this point.
I'd like to understand if this is an anti-pattern, poor code, or what the benefit of this is pattern of a Promise wrapping an Observable and the subscribe method passing next values to other Observables while also resolving the outer Promise? e.g. Promise > Observable > (next(), resolve())
Isn't there a more Observable-all-the-way approach with the use of operators to achieve the same result?
Here is an example of what I have tried to describe above course.service.ts.
@Injectable() export class AcademyCourseService implements Resolve<any> { onCourseChanged: BehaviorSubject<any>; constructor(private _httpClient: HttpClient) { // Set the defaults this.onCourseChanged = new BehaviorSubject({}); } // data resolver used for routing resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> | Promise<any> | any { return new Promise((resolve, reject) => { Promise.all([ this.getCourse(route.params.courseId, route.params.courseSlug) ]).then( () => { resolve(); }, reject ); }); } getCourse(courseId, courseSlug): Promise<any> { return new Promise((resolve, reject) => { this._httpClient.get('api/academy-course/' + courseId + '/' + courseSlug) .subscribe((response: any) => { this.onCourseChanged.next(response); resolve(response); }, reject); }); } } https://stackoverflow.com/questions/66539373/what-is-the-purpose-benefit-of-this-pattern-to-wrap-an-observable-within-a-promi March 09, 2021 at 09:05AM
没有评论:
发表评论