2016-08-31 1 views
0

ログインURL(別のホストとアプリケーション)にナビゲート/リダイレクトすることはできますか?または、アプリケーションのルート内のURLにのみナビゲート/リダイレクトする必要がありますか?認証ガードをAngular 2で開発したいと思っています。ログインURLにナビゲート/リダイレクトできますか?

角度サイトからの例は、アプリケーションのルートが許可されていることを示唆している:


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; 
} 

答えて

1

あなたは()navigateByUrlを試してみましたか?

https://angular.io/docs/ts/latest/api/router/index/Router-class.htmlを参照してください。

But: なぜアプリケーションに含まれていない「外部」URLが必要なのですか? 私は、別々の「ログインページアプリケーション」ではなく、外部のauthServiceであることが最も実践的であると想定しています。またはそのような。

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]); 
 
    } 
 

 
}

関連する問題