Angular 7 Guard-最佳做法

时间:2019-06-21 12:04:45

标签: angular rxjs ngrx

我需要帮助来改进Angular 7 Guard上的代码。 我认为在switchMap上先订阅当前用户以使用它不是一个好习惯。预先,谢谢您的帮助。

import { Injectable } from '@angular/core';
import { CanActivate } from '@angular/router';
import { User } from '@app/core/models/user/user';
import { select, Store } from '@ngrx/store';
import * as fromRoot from '@redux/app.reducers';
import * as invoiceActions from '@redux/payment/subscription/invoice/invoice.actions';
import * as fromSubscription from '@redux/payment/subscription/subscription.reducer';
import * as fromUser from '@redux/user/user.reducers';
import { Observable, of } from 'rxjs';
import { filter, switchMap, take, tap } from 'rxjs/operators';

@Injectable()
export class LoadSubscriptionInvoicesGuard implements CanActivate {
  constructor(private store: Store<fromRoot.AppState>) {
  }

  getFromAPI(user: User): Observable<any> {
    return this.store.pipe(
      select(fromSubscription.selectInvoiceLoaded),
      tap((loaded: boolean) => {
        if (!loaded) {
          this.store.dispatch(new invoiceActions.LoadCollection(user));
        }
      }),
      filter((loaded: boolean) => loaded),
      take(1));
  }

  canActivate(): Observable<boolean> {
    let user : User;
    this.store.pipe(select(fromUser.selectCurrentUser),
    take(1))
    .subscribe((_user: User) => user = _user);

    return this.getFromAPI(user).pipe(
      switchMap(() => of(true)));
  }
}

1 个答案:

答案 0 :(得分:2)

这不是一个坏习惯,但是您的代码并不是最好的。

  canActivate(): Observable<boolean> {
    return this.store.pipe(
      select(fromUser.selectCurrentUser),
      switchMap(user => this.getFromAPI(user)),
      map(value => !!value),
      take(1),
    );
  }

尝试避免拆分的可观察对象:它们是从异步操作开始的,这意味着第二个可观察对象的结果可能在给定时间发生变化。通过这样链接它们,可以防止发生此类副作用。