参数类型 '用户' 的是不能分配给类型 '字符串'

问题描述:

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()的对象。

+0

绝对正确。为什么我不能专注于它 – Pravin

+0

@Pravin碰巧对我们最好的:-) – echonax

+0

感谢等待一分钟来回答 – Pravin