简体   繁体   中英

How to change default home page path ' ' to a different route if there is data in local storage in Angular

I have a default page route location that I want to change if I have some data saved in local storage. For Example: {path: '', redirectTo: "/home", pathMatch: "full" }, I want to change this to /user if I have data stored from previous results.

I would solve it with a guard, since the canActivate method has UrlTree as a return value, which means we can not just protect some route but also redirect to another. This is how to do it:

import { Injectable } from '@angular/core';
import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, UrlTree, Router } from '@angular/router';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class RedirectGuard implements CanActivate {
  constructor(private myLocalStorageWrapperService: LocalStorageWrapperService,
   private router: Router) {}
  
  canActivate(
    route: ActivatedRouteSnapshot,
    state: RouterStateSnapshot): Observable<boolean | UrlTree> | Promise<boolean | UrlTree> | boolean | UrlTree {
    if (this.myLocalStorageWrapperService.hasData()) {
        // redirect to user route
        return this.router.parseUrl("user");
    } else {
       // continue as is
       return true;
    }
  }
}

Replace myLocalStorageWrapperService with your implementation of the window.localStorage wrapper or just remove it and use window.localStorage directly. You would use it inside you route definition:

{ 
  path: '',
  canActivate: [RedirectGuard]
  redirectTo: "/home", 
  pathMatch: "full" 
}

When you subscribe your first datas Object or Array in your component.ts, did you try to use this inside your subscribe? :

 if (this.array.length > 0){
        this.router.navigate(['/route-name']);
      } 

(if > 0 doesn't work, try > 1 )

If you try this, you must inject the router in your constructor parameters to use navigate() .

import { Router } from '@angular/router';


  constructor(private router: Router,...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM