簡體   English   中英

Angular 7 Guard-最佳做法

[英]Angular 7 Guard - Best Practice

我需要幫助來改進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)));
  }
}

這不是一個壞習慣,但是您的代碼並不是最好的。

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

嘗試避免拆分的可觀察對象:它們是異步操作,開始時,這意味着第二個可觀察對象的結果可能在給定時間發生變化。 通過這樣鏈接它們,可以防止發生此類副作用。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM