0
所以我一直在線上教程,有一個簡單的登錄組件,但似乎沒有像我所期望的那樣工作?下面我有一個登錄組件:Angular2獨特的變量設置問題
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。現在在我看來,我期望它是真實的,因爲我在登錄函數運行時設置它。
Many Thanx。羅斯
優秀!謝謝,這麼簡單的錯誤。請注意,這是否適合登錄驗證?我看到其他教程,他們設置localStorage,但從我所知的localStorage是,它可以由客戶端操縱。使用這個布爾變量集似乎更簡單一些,或者當用戶登錄並訪問這些信息而不是將所有內容存儲在localStorage中時設置額外的字段。 – Rossco
如果您僅將loggedIn標誌存儲在內存中,則例如如果他/她刷新頁面或在新標籤中打開鏈接,則用戶不會再登錄。這就是爲什麼使用localStorage或cookie的原因。大多數實際的安全檢查應該由後端完成,而不是由前端完成,所以如果用戶試圖篡改標誌,這應該不成問題。請注意,只需使用調試器將標誌設置爲rue在內存中也很容易。 –
再次感謝您。我使用了localStorage,但是當應用程序運行時,我得到一個內部服務器錯誤'localStorage沒有定義'如果我移動到/ login並登錄,那麼所有工作正常,守衛成功通過。但是,如果我直接回到根目錄,則會出現相同的內部服務器錯誤。有沒有什麼像樣的教程可以提供建議? – Rossco