私はフロントエンドとしてangular2、バックエンドとしてspring/springセキュリティを持つWebアプリケーションで作業しています。Angular2:canActivateは私が認証されていてもログインページにリダイレクトする
すべてが完璧に機能しますが、唯一の問題は、ログインしていてもメンバービューを更新したい場合でも、ログインページにリダイレクトされることです。
AuthGuardサービス:
import { Injectable } from '@angular/core';
import { CanActivate, Router, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';
import {LoginService} from './login.service';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private loginService: LoginService, private router: Router) {}
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): boolean {
let url: string = state.url;
return this.checkLogin(url);
}
checkLogin(url: string): boolean {
if (this.loginService.isAuthenticated) { return true; }
// Store the attempted URL for redirecting
this.loginService.redirectUrl = url;
// Navigate to the login page with extras
this.router.navigate(['/login']);
return false;
}
}
LoginService
import { Injectable } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import { Observable } from 'rxjs/Rx';
import 'rxjs/add/operator/toPromise';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
@Injectable()
export class LoginService {
isAuthenticated: boolean = false;
// store the URL so we can redirect after logging in
redirectUrl: string;
constructor(private http: Http) {
}
login(username: string, password: string) {
const headers = new Headers();
const creds = 'username=' + username + '&password=' + password;
headers.append('Authorization', 'Basic ' + btoa(username + ':' + password));
headers.append('Content-Type', 'application/x-www-form-urlencoded');
return new Promise((resolve) => {
this.http.post('http://localhost:8080/webCustomerTracker/login', creds, { headers: headers })
.map(this.extractData)
.toPromise()//convert to promise
.then(//use then instead of subscribe to form promise chain
success => {
if(success) {
window.localStorage.setItem('auth_key', success.data);
this.isAuthenticated = true;
}
resolve(this.isAuthenticated);
});
}
);
}
logoutAPI(): Observable<any>{
return this.http.get("http://localhost:8080/webCustomerTracker/logout")
.map((res: Response) => res.json())
.catch((error:any) => Observable.throw(error.json().error || ' Server Error '));
}
private extractData(res: Response) {
let body;
// check if empty, before call json
if (res.text()) {
body = res.json();
}
return body || {};
}
}
どうすればいいですか? (私はangular2に新しいです) – SuperGirl
あなたに例を教えてください:) –