Apurv Chaudhary
Apurv Chaudhary

Reputation: 1795

Redirect page with condition from routing file in Angular 5

  1. I want to redirect page from my app-routing.module.ts file
  2. I have two domain i) abcd.in ii) abcd.hk, so i want to redirect in different page from both Domain
  3. Below is my routing file code

    {
        path: 'login',
        loadChildren: './login/login.module#LoginModule',
        canActivate: [GuestGuard],
    },
    {
        path: '',
        loadChildren: './main-page/main-page.module#MainPageModule',
        canActivate: [GuestGuard],
    }
    

I want to redirect on login path when my domain is abcd.hk otherwise on second path

Upvotes: 0

Views: 121

Answers (2)

Hitech Hitesh
Hitech Hitesh

Reputation: 1635

You can do it while checking the

location.hostname

In app.component.ts by taking in router in the constructor

If the

if( location.hostname == "abcd.hk")
   this.router.navigate(['/login]);
    else{
         this.router.navigate(['']);

        }


Upvotes: 2

upinder kumar
upinder kumar

Reputation: 837

try this.

    import { Injectable } from '@angular/core';
    import { CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from 
    '@angular/router';
    import { Observable } from 'rxjs/Observable';
    import { AuthService } from './auth.service';
    import {Router} from '@angular/router';
    @Injectable()
    export class GuestGuard implements CanActivate {
      constructor(private auth: AuthService,
        private myRoute: Router){
      }
      canActivate(
            next: ActivatedRouteSnapshot,
            state: RouterStateSnapshot): Observable<boolean> | Promise<boolean> | boolean {

        this.myRoute.parent.url.subscribe(urlPath => {
          this.url = urlPath[urlPath.length - 1].path;
        });
      }

   if(this.url === 'abcd.hk'){
        this.myRoute.navigate(['/login]);
         return true;
        } else{
          return false;
        }
      }
    }

Upvotes: 0

Related Questions