使用Angular 4和Typescript时,我定义了这个函数
@Injectable() export class XService { display: (message?: string) => Promise<boolean>; } @Component({ templateUrl: './app/x/x.html', styleUrls: ['./app/x/x.component.css'] }) export class XEditComponent { constructor(private _xService: XService ) { } deleteX(): void { let msg = "Do you really want to delete !"; this._xService.display(msg).then((responseOk) => { //..... }); } }
但我总是得到一个TypeError&#39;显示&#39;不是一个功能。
答案 0 :(得分:3)
您实际上没有定义函数。您只定义了它的类型。现在display
将是未定义的。
定义功能:
export class XService {
display: (message?: string) => Promise<boolean> = (message) => {
// Do something more useful here
return Promise.resolve(true);
}
}
或者您可以删除类型声明并让编译器推断出类型:
export class XService {
display = (message: string | undefined): Promise<boolean> => {
// Do something more useful here
return Promise.resolve(true);
}
}
或者您可以将声明更改为方法语法而不是属性语法:
export class XService {
display(message: string | undefined): Promise<boolean> {
// Do something more useful here
return Promise.resolve(true);
}
}