need:
Recently I am working on an online mall project, and the technology is used. There is a very common requirement: the user reads a cookie when clicking the "My" button, and if there is data, it will jump to the personal information page, otherwise it will jump to the registration or login page
solve
This function is implemented here through Angular's route guard.
1. Configure routing information
const routes = [ { path: 'home', component: HomeComponent }, { path: 'product', component: ProductComponent }, { path: 'register', component: RegisterComponent }, { path: 'my', component: MyComponent }, { path: 'login', component: LoginComponent, canActivate: [RouteguardService] },//canActivate is the route guard { path: '', redirectTo: '/home', pathMatch: 'full' } ]
2. Router guard conditions ()
import { Injectable, Inject } from "@angular/core"; import { DOCUMENT } from "@angular/common"; import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router, NavigationStart } from "@angular/router"; import userModel from "./"; @Injectable() export class RouteguardService implements CanActivate { constructor(private router: Router, @Inject(DOCUMENT) private document: any) { } canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean { // ("userId", "18734132326", 10); //Read cookies var cookies = (";"); var userInfo = { userId: "", pw: "" }; if ( > 0) { for (var cookie of cookies) { if (("userId=") > -1) { = ("=")[0]; = ("=")[1]; = false; } } } //Get the current routing configuration information var path = ; if (path == "login") { if (!) { //Read cookies If there is no user information, it will jump to the current login page return true; } else { //If you have logged in, jump to the personal information page. The following statement is routed through ts. (['product']) } } } setCookie(cname, cvalue, exdays) { var d = new Date(); (() + (exdays * 24 * 60 * 60 * 1000)); var expires = "expires=" + (); = cname + "=" + cvalue + "; " + expires; } }
Summarize
The above is what the editor introduced to you to redirect the route through the route guard to jump to the corresponding page according to the conditions. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support for my website!