2016-04-21 69 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);