简体   繁体   English

Angular 7 Guard-最佳做法

[英]Angular 7 Guard - Best Practice

I need help to improve my code on Angular 7 Guard. 我需要帮助来改进Angular 7 Guard上的代码。 I think its not a good practice to first subscribe to the current User to use it after on the switchMap. 我认为在switchMap上先订阅当前用户以使用它不是一个好习惯。 In advance, thank you for your help. 预先感谢您的帮助。

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

It's not a bad practice, but your code is not the best for that. 这不是一个坏习惯,但是您的代码并不是最好的。

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

Try avoiding splitted observables : they're asynchronous operations to begin with, which means the result of the second observable might change at a given time. 尝试避免拆分的可观察对象:它们是异步操作,开始时,这意味着第二个可观察对象的结果可能在给定时间发生变化。 By chaining them like this, you prevent those kind of side effects from happening. 通过这样链接它们,可以防止发生此类副作用。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM