【问题标题】:Argument of type 'User' is not assignable to parameter of type 'string'“用户”类型的参数不可分配给“字符串”类型的参数
【发布时间】:2017-02-15 13:47:34
【问题描述】:

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 “用户”类型的参数不能分配给“字符串”类型的参数。

【问题讨论】:

    标签: angular local-storage


    【解决方案1】:
    localStorage.setItem("user", authenticatedUser);
    

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

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

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

    【讨论】:

    • @Pravin 碰巧发生在我们当中 :-)
    • 如果您不介意在构建应用程序时给出答案,我心中的问题与上述无关像普通的 JavaScript 引擎然后它是如何提高速度的
    • @Pravin 我对 IIS 和 .Net 不熟悉:/
    • 对于任何其他假设您想使用 dist 文件夹构建应用程序。他们是您正在使用的任何其他引擎,还是您使用普通服务器(如 php xmapp)或 java(如 tomcat 等)。
    • @Pravin 我使用 nodejs 的 httpserver 来引导我的应用程序。我已经写了一个关于它的文档:stackoverflow.com/documentation/angular2/789/…
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-03
    • 2019-09-07
    • 2020-06-02
    • 1970-01-01
    • 1970-01-01
    • 2021-06-16
    • 2021-06-30
    相关资源
    最近更新 更多