I am using Angularjs and typescript to outsource some REST-Methods to a factory. This factory should be used by different controllers. So I have a simple webpage, a controller and a factory I would like to use:
Here is the code for the controller:
/// <reference path="../scripts/typescript/angular.d.ts" />
/// <reference path="../scripts/app.ts" />
/// <reference path="ServiceHttp.ts" />
module nawApp {
export interface IStundentScope extends ng.IScope {
fullname: string;
}
export class StudentUse {
private ServiceHttp: any;
constructor($scope: IStundentScope, ServiceHttp: nawApp.ServiceHttp, $http: ng.IHttpService) {
this.ServiceHttp = ServiceHttp;
$scope.fullname = ServiceHttp.exampleFunction();
}
}
StudentUse.$inject = ['$scope', 'ServiceHttp', '$http'];
nawApp.app.controller('StudentUse', StudentUse);
}
And here is my factory:
/// <reference path="../scripts/typescript/angular.d.ts" />
/// <reference path="../scripts/app.ts" />
module nawApp {
export class ServiceHttp {
private http: any;
constructor(public $http: any) {
this.http = $http;
}
public exampleFunction():string {
this.http.get(mainUrl.toString() + 'EventLog').success(function (data, status, headers, config) {
try {
return data;
}
catch (err) {
return "Hello Error";
}
}).error(function (data, status, headers, config) {
return "Hello Error 2";
});
return "Hello Error 3";
}
static Factory($http: ng.IHttpService) {
return new ServiceHttp($http);
}
}
ServiceHttp.$inject = ['$http'];
nawApp.app.factory('ServiceHttp', nawApp.ServiceHttp.Factory);
}
I debugged the code and the Factory($http: ng.IHttpService)... part is executed by using ServiceHttp.exampleFunction(), but the string Hello Error 3 is returned and not the return data; part. If I just copy the HTTP.Get stuff to my controller, everything is fine. I think there is a problem with the way I call the factory.
Can You help me? Thanks!!!
$httpyou don't need adeferred