【发布时间】:2016-11-15 07:14:53
【问题描述】:
所以我一直在关注一个在线教程,并且有一个简单的登录组件,但似乎没有像我预期的那样工作?我在下面有一个登录组件:
import { Component } from '@angular/core';
import { Router } from '@angular/router';
import { FormGroup } from '@angular/forms';
// Services
import { AuthService } from '../../_services/auth.service';
@Component({
styles: [require('./login.component.css')],
template: require('./login.component.html'),
providers: [AuthService]
})
export class LoginComponent {
constructor(private _router: Router, private _authService: AuthService) {
}
login(form) {
var email = form.form._value.email;
var password = form.form._value.password;
var response = this._authService.login(email, password);
if (response) {
this._router.navigate(['dashboard']);
} else {
console.log("error");
}
}
}
在CanActivate路由上设置的认证保护
import { Injectable } from '@angular/core';
import { CanActivate, Router } from '@angular/router';
import { AuthService } from '../_services/auth.service';
@Injectable()
export class AuthGuard implements CanActivate {
constructor(private _router: Router, private _authService: AuthService) {
}
canActivate() {
console.log("auth: " + this._authService.isLoggedIn);
if (this._authService.isLoggedIn == true) {
// logged in so return true
return true;
} else {
// not logged in so redirect to login page
this._router.navigate(['login']);
return false;
}
}
}
最后是我的身份验证服务真正负责登录,这反过来又设置了一个变量,用于我的canActivate 身份验证保护。
import { Injectable } from '@angular/core';
import { Http, Headers, RequestOptions, Response } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map'
@Injectable()
export class AuthService {
isLoggedIn = false;
constructor(private http: Http) { }
login(username, password) {
this.isLoggedIn = true;
console.log("set: " + this.isLoggedIn);
return true;
}
logout() {
this.isLoggedIn = false;
}
}
现在,当我运行登录功能时,isLoggedIn 变量成功设置为 true,但是当导航到仪表板时运行警卫时,变量 isLoggedIn 设置为 false。现在在我看来,我希望它是真的,因为我在登录功能运行时设置了它。
多谢。罗斯
【问题讨论】:
标签: angular angular2-routing angular2-services