Pra*_*vin 1 local-storage angular
认证.service.ts
import {Injectable} from '@angular/core';
import {Router} from '@angular/router';
export class User {
constructor(
public email: string,
public password: string
) { }
}
var users = [
new User('admin@admin.com','adm9'),
new User('user1@gmail.com','a23')
];
@Injectable()
export class AuthenticationService {
constructor(
private _router: Router){}
logout() {
localStorage.removeItem("user");
this._router.navigate(['Login']);
}
login(user){
var authenticatedUser = users.find(u => u.email === user.email);
if (authenticatedUser){
localStorage.setItem("user", authenticatedUser);
this._router.navigate(['Home']);
return true;
}
return false;
}
checkCredentials( ){
if (localStorage.getItem("user") === null){
this._router.navigate(['Login']);
}
}
}
Run Code Online (Sandbox Code Playgroud)
错误
[at-loader] src\app\authentication\authentication.service.ts:32:36 “User”类型的参数不可分配给“string”类型的参数。
localStorage.setItem("user", authenticatedUser);
Run Code Online (Sandbox Code Playgroud)
您的authenticatedUser
变量是 anobject
但您只能string
从本地和会话存储中设置/获取 s 。所以你可能会做这样的事情:
localStorage.setItem("user", JSON.stringify(authenticatedUser));
Run Code Online (Sandbox Code Playgroud)
当你需要获取该项目时,你应该JSON.parse()
再次将其传递给一个对象。
归档时间: |
|
查看次数: |
6963 次 |
最近记录: |