我知道可以使用@ngrx/router-store 将路由存储在一个状态中。
这个库将 Angular 路由器与 ngrx-store 绑定。
按照redux的原则,存储路由是有道理的,因为它是应用程序的状态变化,但是,实际上,存储的信息怎么办?只有当我们想在路由上实现副作用时它才有用吗?
我知道可以使用@ngrx/router-store 将路由存储在一个状态中。
这个库将 Angular 路由器与 ngrx-store 绑定。
按照redux的原则,存储路由是有道理的,因为它是应用程序的状态变化,但是,实际上,存储的信息怎么办?只有当我们想在路由上实现副作用时它才有用吗?
根据我的经验,它不仅仅是为了效果。有时您可能需要传递前一个状态的参数 id。1. 例如,如果您正在加载购物车详细信息(假设是电子商务应用程序)。当有人点击 url 并将参数存储在本地存储中并将其传递给不同的状态 url 时,您可以获得参数 id。
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
const quickCartId = route.firstChild.firstChild.params.id; //get the previous state of params id
if (!this.auth.isAuthenticated()) {
this.auth.handleAuthenticationURLEntry(state);
this.auth.login();
return false;
}
// logic for quick cart feature
if (!!quickCartId) {
localStorage.setItem(environment.cartId, quickCartId); // replace the id
this.cartProvider.load();
}
return true;
}
希望能帮助到你
同理,不会因为ngrx而改变。
import { NewTicketComponent } from './components/ticket/new-ticket/new-ticket/new-ticket.component';
import { RouterModule, Routes } from '@angular/router';
import { NgModule } from '@angular/core';
import { HomeComponent } from './components/home/home.component';
import { DashboardComponent } from './components/dashboard/dashboard.component';
import { RegisterComponent } from './components/register/register.component';
import { LoginComponent } from './components/login/login.component';
import { ProfileComponent } from './components/profile/profile.component';
import { PublicProfileComponent } from './components/public-profile/public-profile.component';
// Our Array of Angular 2 Routes
const appRoutes: Routes = [
{
path: '',
component: HomeComponent // Default Route
},
{
path: 'dashboard',
component: DashboardComponent, // Dashboard Route,
canActivate: [AuthGuard] // User must be logged in to view this route
},
{
path: 'register',
component: RegisterComponent, // Register Route
canActivate: [AuthGuard] // User must be logged in to view this route
},
{
path: 'login',
component: LoginComponent, // Login Route
canActivate: [NotAuthGuard] // User must NOT be logged in to view this route
},
{
path: 'user/:id',
component: ProfileComponent, // Profile Route
canActivate: [AuthGuard] // User must be logged in to view this route
},
{
path: 'profile/user/:username',
component: PublicProfileComponent, // Public Profile Route
canActivate: [AuthGuard] // User must be logged in to view this route
},
{ path: '**', component: HomeComponent } // "Catch-All" Route
];
@NgModule({
declarations: [],
imports: [RouterModule.forRoot(appRoutes)],
providers: [],
bootstrap: [],
exports: [RouterModule]
})
export class AppRoutingModule { }
例如,我在选择器中使用路由参数
export const selectCurrentCustomer = createSelector(
selectCustomers,
selectRouteParameters,
(customers, route) => customers[route.customerId]
);
同样如docs中所述,@ngrx/router-store 还调度导航操作。