我知道可以使用@ngrx/router-store在状态中存储路由。
这个库将Angular路由器与ngrx-store绑定在一起。
遵循redux原则,存储路由是有意义的,因为它是应用程序的状态更改,但实际上,如何处理存储的信息?只有当我们想在路由上实现副作用时,它才有用吗?
发布于 2018-08-07 01:19:23
同样的,也不会因为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 { }
发布于 2018-08-07 05:50:58
从我的经验来看,这不仅仅是为了效果。有时,您可能需要传递前一个状态的params id。1.装入购物车详细信息时的示例(假设是电子商务应用程序)。当有人点击url时,你可以获得参数id,并将参数存储在本地存储中,并将其传递给不同状态的url。
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;
}
希望能有所帮助
发布于 2018-08-07 19:16:09
我在选择器中使用route params,例如
export const selectCurrentCustomer = createSelector(
selectCustomers,
selectRouteParameters,
(customers, route) => customers[route.customerId]
);
此外,正如在docs中提到的,@ngrx/router-store也会分派导航操作。
https://stackoverflow.com/questions/51711639
复制相似问题