参数类型 '用户' 的是不能分配给类型 '字符串'
问题描述:
authentication.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('[email protected]','adm9'),
new User('[email protected]','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']);
}
}
}
错误
[在装载机] SRC \应用\认证\认证的参数.service.ts:32:36 'User'类型的参数不能分配给'string'类型的参数。
答
localStorage.setItem("user", authenticatedUser);
你authenticatedUser
变量是一个object
但你只能设置/本地和会话存储获得string
秒。所以,你可能做的是这样的:
localStorage.setItem("user", JSON.stringify(authenticatedUser));
而当你需要获得该项目则应该重新它JSON.parse()
的对象。
绝对正确。为什么我不能专注于它 – Pravin
@Pravin碰巧对我们最好的:-) – echonax
感谢等待一分钟来回答 – Pravin