K
K
kachurynets2021-04-26 11:07:33
Angular
kachurynets, 2021-04-26 11:07:33

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
        }
      })
    );
  }


Service

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

1 answer(s)
A
Anton Shvets, 2021-04-27
@kachurynets

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 }),
      )

then in the service
getAdministrators() {
  return this.http.get<IAdministrator[]>(`api/v1/admin/users`).pipe(handler())
}

we transfer all prefixes to the url to the interceptor
in the component, we make the data source through pipe (map (...))
Observables are displayed in the template through async pipes. And that's it, explicit subscriptions are not needed here.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question