Reputation: 1019
I'm trying to make use of my API with AngularJS; I made a service which I'm now trying to load into a controller, but I'm seeing some errors.
Unknown provider: ApiServiceProvider <- ApiService <- ManageIntranetController
I'm using TypeScript.
My service looks like this:
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);
})
};
}
}
}
And my controller looks like this:
/// <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"));
}
}
}
Upvotes: 1
Views: 165
Reputation: 13997
Your error means that it does not know of the service "ApiService". You probably forgot to register it on your module:
angular.module("myApp", [])
.controller("ManageIntranetController", Controllers.ManageIntranetController)
.service("ApiService", Services.ApiService);
Also, your service won't work, because you cannot inject a $scope
in it. Instead, do something like this:
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' }
});
};
}
}
and in your controller:
ApiService.getIntranetItems("get").then((data) => {
$scope.intranetItems = data;
});
Upvotes: 1
Reputation: 834
You still need to register your services/controllers with angular. For example, you register a controller like this:
angular
.module('app')
.controller('myCtrl', MyController); //where MyController is a TypeScript class
For services is a bit more complex. You either need to add a static function within your class which returns an instance, call that function when registering the service with angular, or (my personal preference), create a javascript function outside the Class like so:
function factory($q: ng.IQService): MyService {
return new MyService($q);
}
angular
.module('app')
.factory('myService', factory);
Upvotes: 1