2017-02-15 76 views
1

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'類型的參數。

回答

2
localStorage.setItem("user", authenticatedUser); 

authenticatedUser變量是一個object但你只能設置/本地和會話存儲獲得string秒。所以,你可能做的是這樣的:

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

而當你需要獲得該項目則應該重新它JSON.parse()的對象。

+0

絕對正確。爲什麼我不能專注於它 – Pravin

+0

@Pravin碰巧對我們最好的:-) – echonax

+0

感謝等待一分鐘來回答 – Pravin

相關問題