为什么这不是一个功能

时间:2016-08-07 21:49:38

标签: typescript aurelia

出于某种原因authenticationProvider似乎缺失了。

@autoinject()
export class ProviderManager implements AuthenticationManager {
   constructor( private container: Container ){
   }
    public authenticate( creds: Credentials ): Promise<Authentication> {
        var provider = creds.authenticationProvider();
        return this.container.get( provider ).authenticate( creds );
    }

}

Credentials

export interface Credentials {
    authenticationProvider(): { new(): AuthenticationManager };
}

实施UsernamePasswordCredentials

export class UsernamePasswordCredentials implements Credentials {

    public authenticationProvider(): {new(): AuthenticationManager} {
        return HttpBasicAuthentication;
    }

    user: String;
    pass: String;
}

AuthenticationManager

export interface AuthenticationManager {
    authenticate( creds: Credentials ): Promise<Authentication>;
}

Login

@autoinject()
export class Login {
    private log: Logger = LogManager.getLogger( Login );
    creds: UsernamePasswordCredentials;

    constructor( private am: AuthenticationManager, private router: Router ) {
    }

    public signIn(): void {
        this.log.debug( `authenticating ${ this.creds.user }` );
        this.am.authenticate( this.creds ).then( auth => {
            var route = Route.MANAGE_CONTENT;
            this.log.debug( `navigating to ${ route }` );
            var router = this.router;
            router.navigate( route );
        } ).catch( error => {
            this.log.error( error );
        } );
    }
}

这是Chrome的堆栈跟踪

   VM802:1 Uncaught TypeError: creds.authenticationProvider is not a function(…)(anonymous function) @ VM802:1
authenticate @ ProviderManager.ts:13
signIn @ login.ts:22evaluate @ aurelia-binding.js:1522
callSource @ aurelia-binding.js:4963
(anonymous function) @ aurelia-binding.js:4987
handleDelegatedEvent @ aurelia-binding.js:3176

1 个答案:

答案 0 :(得分:1)

感谢您分享Login代码。

您排在正确的位置,但似乎this.creds之前未定义。

代码

class Login {
    creds: UsernamePasswordCredentials;
}

告诉Typescript它期望信用证属于UsernamePasswordCredentials类型。但它没有什么可以初始化creds字段...特别是,当上面的内容被转换时,不会为该行发出javascript(https://www.typescriptlang.org/play/可能有助于查看转换器的作用)。

这意味着,在signIn方法中,this.creds将是未定义的。

这类似于C#,如果您没有初始化字段,则默认为null

虽然Typescript可以捕获很多东西,但是当变量在运行时具有未定义/ null值时,它不能(总是)捕获,就像C#这样的静态类型语言仍然可以最终生成触发null的编译代码参考例外。

编辑:啊,我的道歉。如果creds未定义,您将收到ReferenceError: creds is not definedTypeError应该明确creds已在其他位置填充,但类型错误。