如何将接口作为参数传递并在 TypeScript 中获得匿名回调?

Man*_*Das 2 typescript angular2-services angular

这是代码,我试图实现:

this._customHttp.httpPostService('app/fetchGridDetails',this.req,new  
  InterfaceName() {
         onEvent(str :string) {
            console.log(str);
         }
    });
Run Code Online (Sandbox Code Playgroud)

Fra*_*ica 5

如果它是一个接口而不是一个类,你就不用new它了。您可以创建一个实现内联接口的对象:

this._customHttp.httpPostService('app/fetchGridDetails', this.req,
    <InterfaceName>{
        onEvent(str: string) {
            console.log(str);
        }
    });
Run Code Online (Sandbox Code Playgroud)

您甚至可能不需要显式编写接口名称。如果该对象具有 预期的正确方法,则httpPostServiceTypeScript 应编译它:

this._customHttp.httpPostService('app/fetchGridDetails', this.req,
    {
        onEvent(str: string) {
            console.log(str);
        }
    });
Run Code Online (Sandbox Code Playgroud)