2016-07-05 65 views
6

我轉換這個代碼爲最新角2 authentication.service.ts打字稿 - 參數「U」隱含有一個「任意」類型

應的代碼是什麼樣子?

app/auth/auth.service.ts(30,40): error TS7006: Parameter 'u' implicitly has an 'any' type. 

// services/auth.service.ts 
import {Injectable} from '@angular/core'; 
import {Router} from '@angular/router'; 

//http://4dev.tech/2016/03/login-screen-and-authentication-with-angular2/ 
//https://github.com/leonardohjines/angular2-login 
export class User { 
    constructor(
    public email: string, 
    public password: string) { } 
} 

var users:any = [ 
    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:any){ 
    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']); 
    } 
    } 
} 
+0

你見過這個錯誤的修復嗎? –

回答

9

你可以嘗試使用User類型,而不是any

var users:User[] = [ 
    (...) 
]; 

var authenticatedUser = users.find((u:User) => u.email === user.email); 
2

的問題的原因是沒有正確定義的參數,因爲這種情況下是以下示例中的變量「u」:

var authenticatedUser = users.find(u => u.email === user.email); 
,如果你沒有服務的類模型

,應該定義爲「U」當你在當下所需要的字符串或其它類型:

var authenticatedUser = users.find(u:string => u.email === user.email); 
0

我使用你已經使用了相同的例子。

而不是應用任何,請將參數類型設置爲User

所以,你的登錄方法是這樣的:

login(user: User): boolean { ...

然後,刪除任何引用any關鍵詞。

-2

變化

tsconfig.json文件

「noImplicitAny」:假,

並添加

'NG2-formly':「NPM:NG2-formly /捆綁/ ng2- formly.umd.js',

到systemjs.config.js

7

考慮使用(u:any)=> ...