如何使用AngularJS和TypeScript调用Web API操作?

时间:2014-08-29 13:04:53

标签: angularjs asp.net-web-api typescript

我需要从AngularJS调用我的webAPI操作。我可以做简单的CRUD,但如果我想调用特定的动作,我应该怎么称呼它?

例如,我可以通过从AngularJS 资源中调用保存来调用POST。

以下是我使用的TypeScript代码:

Link to the source of the code

 /// <reference path="../models/ILogin.ts" />

 module App.Resources {
 "use strict";

 export interface ILoginResourceDef
 extends ng.resource.IResource<Models.ILogin> {
 }
}


/// <reference path="ILoginResourceDef.ts" />

 module App.Resources {
"use strict";

export interface ILoginResource
extends ng.resource.IResourceClass<Resources.ILoginResourceDef> {
}
} 


/// <reference path="../models/ILogin.ts" />
/// <reference path="../models/Login.ts" />
/// <reference path="../resources/ILoginResource.ts" />
/// <reference path="../scope/ILoginScope.ts" />


module App.Controllers {
"use strict";

export class AccountController {
    constructor(private $scope: Scope.ILoginScope, private loginResource: Resources.ILoginResource) {
        $scope.newLogin = new Models.Login();
    }

    public login(): void {
        this.loginResource.save(this.$scope.newLogin,  // This save trigger the POST
            () => this.logme(),
            () => { alert('failure'); });
    }

2 个答案:

答案 0 :(得分:1)

这就是我做了什么,我做了一个不同的服务,并将服务注入控制器

module portal.services {

export class apiService {


    public getData<T>(url?:string): ng.IPromise<T> {

        var def = this.$q.defer();
        this.$http.get(this.config.apiBaseUrl + url).then((successResponse) => {

            if(successResponse)
                def.resolve(successResponse.data);
            else
                def.reject('server error');

        }, (errorRes) => {

            def.reject(errorRes.statusText);
        });

        return def.promise;
    }

    public postData<T>(formData: any, url?:string,contentType?:string): ng.IPromise<T>{

        var def = this.$q.defer();

        this.$http({
            url: this.config.apiBaseUrl + url,
            method: 'POST',
            data:formData,
            withCredentials: true,
            headers: {
                'Content-Type':contentType || 'application/json'
            }
        }).then((successResponse)=>{
            def.resolve(successResponse.data);
        },(errorRes)=>{
            def.reject(errorRes);
        });

        return def.promise;

    }

    static $inject = ['$q','$http', 'config'];

    constructor(public $q:ng.IQService,public $http:ng.IHttpService, public config:interfaces.IPortalConfig) {


    }

}

}

答案 1 :(得分:0)

  

我可以做简单的CRUD,但如果我想调用特定的动作,我应该怎么称呼它?

您可以使用原始$http将您的调用设计为完全您希望的方式。 https://docs.angularjs.org/api/ng/service/ $ http