Extending $resource of angularjs using IResourceClass of typescript

后端 未结 2 680
眼角桃花
眼角桃花 2021-02-13 10:26

I am developing SPA using Asp.Net Web API and AngularJS. I also use TypeScript to get static typing. So, I added DefinitelyTyped angularjs.

As I am using RESTfull servic

2条回答
  •  旧时难觅i
    2021-02-13 10:44

    I totally agree with Scott's answer: https://stackoverflow.com/a/21786326/2677975

    I do have one addition: In my project, I've create the class ServiceModel, which implements the interface IActionDescriptor.

    module Common.ApiService {
        export class HttpHeaders {
            'Content-Type': string;
            Accept: string;
        }
    
        export class ServiceModel implements ng.resource.IActionDescriptor {
            public method: string = 'GET';
            public params: T;
            public isArray: boolean = false;
            public url: string;
            public headers: HttpHeaders = new HttpHeaders()
        } 
    }
    

    Then, I can setup the method in my controller, just as Scott did, but now, the IDE will have type completion on the headers (and the params later on)

    export interface IProfileServiceResource extends ng.resource.IResourceClass {
        SaveProfileImage(profileImageUri: Profile.Model.UserProfileModel): ng.resource.IResource>;
    }
    
    export class ProfileApiService 
        implements Common.ApiService.IApiServiceBase {
    
        public SaveProfileImage: Common.ApiService.ServiceModel;
    
        constructor() {    
            this.SaveProfileImage = new Common.ApiService.ServiceModel();
            this.SaveProfileImage.method = "POST";
            this.SaveProfileImage.url = "/api/Profile/SaveProfileImage";
            this.SaveProfileImage.headers["Content-Type"] = 'application/json';
    }
    

    I made this as an additional answer, since it only serves to provide types for the headers and the params.

提交回复
热议问题