[英]How to use the router state in an Angular application with ngrx implementation
我知道可以使用@ ngrx / router-store将状态存储在路由中。
该库将Angular路由器与ngrx-store绑定。
遵循redux原则,存储路由是有意义的,因为它是应用程序的状态更改,但是实际上,如何处理存储的信息? 仅当我们要在路由上实现副作用时,它才有用吗?
同样,不会因为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 { }
根据我的经验,这不仅是为了效果。 有时您可能需要传递先前状态的params id。 1.例如,如果您要加载购物车详细信息(假设是电子商务应用程序)。 当有人点击url并将其存储在本地存储中并将其传递给其他状态url时,您可以获得params 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;
}
希望能帮助到你
例如,我在选择器内使用路由参数
export const selectCurrentCustomer = createSelector(
selectCustomers,
selectRouteParameters,
(customers, route) => customers[route.customerId]
);
另外,如docs中所述,@ ngrx / router-store也调度导航动作。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.