-2

我想在用户第一次访问我的网站时触发一个动作。使用 ngxs 执行此操作的最佳方法是什么?我发现有一个叫做 NgxsOnInit 的东西,但我不知道它是如何触发的。

4

1 回答 1

2

NgxsOnInit 是您在状态类中实现的接口。

一个很好的用途是在第一次加载状态时调度动作。

// auth.actions.ts
export class CheckSession() {
  static readonly type = 'auth/check-session';
}


// auth.state.ts
import { State, Action, NgxsOnInit } from '@ngxs/store';

export interface AuthStateModel {
  token: string;
}

@State<AuthStateModel>({
  name: 'auth',
  defaults: {
    token: null
  }
})
export class AuthState implements NgxsOnInit {

  ngxsOnInit(ctx: StateContext<AuthStateModel>) {
    ctx.dispatch(new CheckSession());
  }

  @Action(CheckSession)
  checkSession(ctx: StateContext<AuthStateModel>, action: CheckSession) {
    ...
  }
}

但是,如果您需要根据 url 获取一些信息,最好创建一个路由守卫来调度操作,然后使用它store.selectOnce从状态中检索您需要的值。

import { Injectable } from '@angular/core';
import { ActivatedRouteSnapshot, CanActivate, RouterStateSnapshot } from '@angular/router';
import { Store, ofAction } from '@ngxs/store';
import { Observable, of } from 'rxjs';
import { tap, map, catchError } from 'rxjs/operators';

import { GetProject } from './project.action';
import { ProjectState } from './project.state';

@Injectable({
  providedIn: 'root'
})
export class ProjectGuard implements CanActivate {

  constructor(private store: Store) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {
    const projectId = route.paramMap.get('projectId');

    // we call the store which downloads the project, we then wait for the action handler to return the project
    return this.store.dispatch(new GetProject(projectId)).pipe(
      // we convert the project to a boolean if it succeeded
      map(project => !!project),

      // we catch if the GetProject action failed, here we could redirect if we needed
      catchError(error => {
        return of(false);
      })
    );
  }
}

// 应用路由

{ path: 'project/:projectId', loadChildren: './project#ProjectModule', canActivate: [ProjectGuard] },
于 2018-05-23T18:05:01.023 回答