要展示Angular 5中使用NGXS和路由解析器的解决方案,可以按照以下步骤操作:
npm install @ngxs/store @ngxs/router-plugin
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { NgxsModule } from '@ngxs/store';
import { NgxsRouterPluginModule } from '@ngxs/router-plugin';
import { MyState } from './my-state';
import { MyComponent } from './my-component';
@NgModule({
imports: [
CommonModule,
NgxsModule.forFeature([MyState]),
NgxsRouterPluginModule.forRoot(),
],
declarations: [MyComponent],
})
export class MyModule {}
import { State, Action, StateContext } from '@ngxs/store';
import { Navigate } from '@ngxs/router-plugin';
export class MyStateModel {
public data: any;
}
@State({
name: 'myState',
defaults: {
data: null
}
})
export class MyState {
@Action(Navigate)
navigate(ctx: StateContext, action: Navigate) {
// 在路由导航时执行的操作
const { state } = action.routerState;
ctx.patchState({ data: state.data });
}
}
import { Component } from '@angular/core';
import { Select } from '@ngxs/store';
import { MyStateModel } from './my-state';
@Component({
selector: 'app-my-component',
template: `
{{ data }}
`,
})
export class MyComponent {
@Select(state => state.myState.data) data$: Observable;
}
import { Component } from '@angular/core';
import { Store } from '@ngxs/store';
import { Navigate } from '@ngxs/router-plugin';
@Component({
selector: 'app-root',
template: `
`,
})
export class AppComponent {
constructor(private store: Store) {}
navigateToDataRoute() {
const data = 'Some data';
this.store.dispatch(new Navigate(['/data-route'], { data }));
}
}
这就是使用NGXS和路由解析器的基本解决方案。你可以根据你的需求进行自定义和扩展。