2014-08-29 43 views
0

我需要從AngularJS調用我的webAPI動作。我可以做簡單的CRUD,但如果我想調用特定的操作,應該如何調用它?如何使用AngularJS和TypeScript調用WebAPI動作?

比如我可以通過從AngularJS 資源調用保存來電來郵。

這裏是打字稿代碼我使用:

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'); }); 
    } 

回答

1

這裏是我做的我做了一個不同的服務和注入服務控制器

模塊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) { 


    } 

} 

}

相關問題