Answer the question
In order to leave comments, you need to log in
How to avoid subscription in Angular service?
Is it possible in my case to use a subscription in the service?
How can we avoid the subscription here and make the code better?
Component
public getUsers(): void {
this.isLoading = true;
this.sub.add(
this.adminService.getAdministrators().subscribe((administrators) => {
if (administrators) {
this.administrators = administrators;
this.dataSource.data = administrators.map(user => {
return new Administrator(user);
});
this.isLoading = false
}
})
);
}
public administrators: BehaviorSubject<any> = new BehaviorSubject<any>([]);
public administrators$: Observable<any> = this.administrators.asObservable();
constructor(private http: HttpClient) {}
public getAdministrators(): Observable<IAdministrator[]> {
if (!this.administrators.value.length) {
this.http.get(`${environment.baseUrl}/api/v1/admin/users`).pipe(
tap((response) => {
this.administrators.next(response);
})
).subscribe();
}
return this.administrators.asObservable();
}
Answer the question
In order to leave comments, you need to log in
delete this bunch of code and make an operator (call it as you like)
export const handler = <T>() => pipe(
map((value: T) => ({ loading: false, value })),
startWith({ loading: true }),
catchError(error => of({ loading: false, error })),
shareReplay({ refCount: true, bufferSize: 1 }),
)
getAdministrators() {
return this.http.get<IAdministrator[]>(`api/v1/admin/users`).pipe(handler())
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question