2016-08-31 8 views
0

Können wir zu einer beliebigen Login-URL (anderer Host und Anwendung) navigieren/umleiten oder müssen wir nur innerhalb der Routen unserer Anwendung zu URLs navigieren/umleiten?Wir wollen in Angular 2 einen Authentifizierungswächter entwickeln. Können wir zu einer Login-URL navigieren/umleiten?

Das Beispiel aus der Winkel Seite schlägt nur Anwendung Routen erlaubt:


canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) { 
    if (this.authService.isLoggedIn) { return true; } 

    // Store the attempted URL for redirecting 
    this.authService.redirectUrl = state.url; 

    // Navigate to the login page 
    this.router.navigate(['/login']); 
    return false; 
} 

Antwort

1

Haben Sie navigateByUrl versucht()?

Siehe https://angular.io/docs/ts/latest/api/router/index/Router-class.html für die Verwendung.

Aber: Warum benötigen Sie eine "externe" URL, die nicht Teil Ihrer Anwendung ist? Ich gehe davon aus, dass ein externer authService statt einer separaten "Login-Page-Application" am besten praktikabel ist. oder so.

z.B.

import { Injectable }  from '@angular/core'; 
 
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router} from '@angular/router'; 
 
import {Observable} from "rxjs"; 
 
import {AuthService} from "../services/auth.service"; 
 

 
@Injectable() 
 
export class LoginGuard implements CanActivate { 
 

 
    constructor(protected router: Router, protected authService: AuthService) { } 
 

 
    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean { 
 
    console.log('AuthGuard#canActivate called'); 
 

 
    if (state.url !== '/login' && !this.authService.isLoggedIn()) { 
 
     this.router.navigate(['/login'], {queryParams: {redirectTo: state.url}}); 
 
     return false; 
 
    } 
 

 
    return true; 
 
    } 
 
}

import {Component} from "@angular/core"; 
 
import {ActivatedRoute, Router} from "@angular/router"; 
 

 
@Component({ 
 
    templateUrl: "app/components/login/login.html" 
 
}) 
 
export class LoginComponent { 
 

 
    constructor(public route: ActivatedRoute, public router: Router) { } 
 

 
    loginSuccessful() { 
 
    let redirect = this.route.snapshot.queryParams['redirect']; 
 
    let redirectUrl = redirect != null ? redirect : '/dashboard/'; 
 
    console.log('redirect to: ' + redirect); 
 
    this.router.navigate([redirectUrl]); 
 
    } 
 

 
}

Verwandte Themen