当前位置: 动力学知识库 > 问答 > 编程问答 >

angularjs - Angular $resource - accessing to returned resource.$promise in TypeScript

问题描述:

I'need to access the $promise property of object returned with some default action on $resource (e.g. remove, query...). But it seems it is not possible in current TypeScript definitions for $resource:

Example:

I have a student resource:

interface IStudentDataModel {

name: string

age: number

}

interface IStudentResource extends IResourceClass<IStudentDataModel> {

deactivate(params: Object): IResource<IStudentDataModel>

}

export default function ($resource: IResourceService, CONFIG: IConfig): IStudentResource {

"ngInject"

let deactivateAction: IActionDescriptor = {

url: `${CONFIG.api_host}/students/:studentId/deactivate`,

method: 'PUT'

}

return <IStudentResource>$resource(

`${CONFIG.api_host}/students/:studentId`,

}

studentId: '@studentId'

},

{

deactivate: deactivateAction,

});

}

Then I'm using this resource in another service:

export default class StudentActions {

constructor(

private StudentResource: IStudentResource,

) {

"ngInject"

}

deactivate(studentId: number): IPromise<any> {

return this.StudentResource.deactivate({ studnetId: studentId}).$promise;

}

remove(studentId: number): IPromise<any> {

return this.StudentResource.remove({ studentId: studentId}).$promise; //!!!

}

}

PROBLEM: I can't access to the this.StudentResource.remove({ studentId: studentId}).$promise because default actions have IStudentDataModel as return trype instead of IResource<IStudentDataModel> (but it returns resource with $promise property, not only data model).

I've tried to override the remove method in IStudentResource:

interface IStudentResource extends IResourceClass<IStudentDataModel> {

deactivate(params: Object): IResource<IStudentDataModel>

remove(params: Object): IResource<IStudentDataModel>

}

But compiler says:

Interface 'IStudentResource' incorrectly extends interface

'IResourceClass'. Types of property 'remove' are

incompatible.

Type '(data: Object) => IResource' is not assignable to type 'IResourceMethod'.

网友答案:

It's a bit crude but you can use a type assertion to any in order to make the type checking stop complaning.

return (<any>this.StudentResource.deactivate({ studnetId: studentId})).$promise;

Also since the typescript interfaces are open ended you can also amend the IResource interface to add the $promise property.

interface IResourceClass<T> {
    $promise: IPromise<T>
}
分享给朋友:
您可能感兴趣的文章:
随机阅读: