Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

angular - Angular2 conditional routing

This might be a basic question, but in Angular2 is there any way to do conditional routing ? Or, would someone do that outside the router ?

I know ui-router had some ability to do this, but I haven't seen anything similar in Angular2s router

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

As mentioned, Angular Route Guards are a good way to implement conditional routes. Since the Angular Tutorial is a bit wordy on the topic, here is a short summary how to use them with an example.

1. There are several types of guards. If you need something of the logic if (loggedIn) {go to "/dashboard"} else { go to "/login"}, then what you are looking for is the CanActivate-Guard. CanActivate can be read as "The new route X can be activated if all of the conditions Y are satisfied". You can also define side-effects like redirects. If this doesn't fit your logic, checkout the Angular Tutorial page to see the other guard types.

2. Create an auth-guard.service.ts.

3. Populate the auth-guard.service.ts with the following code:

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

@Injectable()
export class AuthGuardService implements CanActivate {

  constructor(
    private router: Router
  ) {}

  canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
    const isLoggedIn = false; // ... your login logic here
    if (isLoggedIn) {
      return true;
    } else {
      this.router.navigate(['/login']);
      return false;
    }
  }

}

4. Register the auth-guard.service.ts in your route-module. Also, add the key-value pair canActivate:[AuthGuardService] to all routes you want to guard. It should look somewhat like this:

const appRoutes: Routes = [
  { path: '', component: LandingComponent},
  { path: 'login', component: LoginComponent},
  { path: 'signup', component: SignUpComponent},
  { path: 'home', component: HomeComponent, canActivate: [AuthGuardService]},
  { path: 'admin', component: AdminComponent, canActivate: [AuthGuardService]},
  { path: '**', component: PageNotFoundComponent }
];

@NgModule({
  imports: [
    RouterModule.forRoot(appRoutes)
  ],
  exports: [
    RouterModule
  ],
  providers: [
    AuthGuardService
  ]
})
export class AppRoutingModule { }

That should get you started.

Here's a minimalistic demo: https://stackblitz.com/edit/angular-conditional-routing


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...