2016-04-21 63 views
1

我想使用我的API與AngularJS;我做了一個服務,我現在試圖加載到一個控制器,但我看到一些錯誤。AngularJS服務注入器錯誤

Unknown provider: ApiServiceProvider <- ApiService <- ManageIntranetController 

我正在使用TypeScript。

我的服務是這樣的:

module Services { 
    export class ApiService { 

     getIntranetItems: (action: string) => any; 

     constructor($scope, $http: ng.IHttpService) { 

      this.getIntranetItems = (action: string) => { 
       return $http({ 
        method: "GET", 
        url: "https://localhost:44326/api/intranet/" + action, 
        headers: { 'Content-Type': 'application/json' } 
       }).success(function (data) { 
        $scope.intranetItems = data; 
       }).error(function (msg) { 
        alert("ERROR: " + msg); 
       }) 
      }; 

     } 
    } 
} 

我的控制器看起來像這樣:

/// <reference path="../services/apiservice.ts" /> 


module Controllers { 
    export interface IManageIntranetController extends ng.IScope { 

    }  

    export class ManageIntranetController { 
     constructor($scope: IManageIntranetController, ApiService: Services.ApiService) { 
      console.log(ApiService.getIntranetItems("get")); 
     } 
    } 
} 
+0

有您註冊的角模塊上的服務?例如'angular.module(「myApp」,[])。service(「ApiService」,Services.ApiService);' – devqon

+0

另外,你不能注入'$ scope'到一個服務中,只有一個控制器和指令 – devqon

+0

@devqon我沒有那樣做,但現在我仍然一直在接受相同的錯誤..哦,好的,我會改變這種情況。 – Peurr

回答

1

你的錯誤意味着它不知道服務「ApiService」。你可能忘了將其註冊模塊上:

angular.module("myApp", []) 
    .controller("ManageIntranetController", Controllers.ManageIntranetController) 
    .service("ApiService", Services.ApiService); 

此外,您的服務將無法正常工作,因爲你不能注入中有一個$scope。取而代之的是,做這樣的事情:

export class ApiService { 

    getIntranetItems: (action: string) => any; 

    constructor($http: ng.IHttpService) { 

     this.getIntranetItems = (action: string) => { 
      return $http({ 
       method: "GET", 
       url: "https://localhost:44326/api/intranet/" + action, 
       headers: { 'Content-Type': 'application/json' } 
      }); 
     }; 

    } 
} 

和控制器:

ApiService.getIntranetItems("get").then((data) => { 
    $scope.intranetItems = data; 
}); 
+0

很好的答案,我認爲注入'$ scope'會導致錯誤。 – Peurr

1

你仍然需要用角來註冊你的服務/控制器。例如,您註冊一個像這樣的控制器:

angular 
    .module('app') 
    .controller('myCtrl', MyController); //where MyController is a TypeScript class 

對於服務有點複雜。註冊有角,或(我的個人偏好)服務時,您可能需要您的類返回一個實例中添加一個靜態函數,調用該函數,創建一個JavaScript函數的類外,像這樣:

function factory($q: ng.IQService): MyService { 
    return new MyService($q); 
} 

angular 
    .module('app') 
    .factory('myService', factory);