类型'用户'的论点不能分配给' string'

时间:2017-02-15 05:39:04

标签: angular local-storage

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('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']);
  }
 } 
}

错误

  

[at-loader] src \ app \ authentication \ authentication.service.ts:32:36       类型'用户'的论点不能分配给' string'。

类型的参数

1 个答案:

答案 0 :(得分:2)

localStorage.setItem("user", authenticatedUser);

您的authenticatedUser变量是object,但您只能从本地和会话存储中设置/获取string。所以你可能会这样做:

localStorage.setItem("user", JSON.stringify(authenticatedUser));

当您需要获取该项目时,您应该JSON.parse()再次将其添加到对象中。