Provider必须从$ get factory方法返回一个值

时间:2015-09-08 09:23:55

标签: angularjs typescript

我正在努力解决Angular和Typescript的问题。

module App {
    declare var environment;

    export var app: ng.IModule = angular.module("budgetsApp", [])..factory("Company", CompanyFactory)
        .controller('mainMenuController', MainMenuController);  



--Typescript file  
module App {
    declare var _;  //the underscore library

    export interface ICompanyResult {
        companyId: number;
        name: string;
    }

    export interface ICompanyFactoryFindResults {
        count: number;
        values: ICompanyResult[];
    }

    export class CompanyFactory {
        static $inject = ['$http'];

        private $http: any;

        constructor($http: ng.IHttpService) {
            this.$http = $http;
        }

        public find(searchTerm: any, limit: any): ICompanyFactoryFindResults {
            return this.$http
                .get('api/company')
                .then((result) => {
                    var results = _.filter(result.data, (item) => {
                        return item.name.search(new RegExp(searchTerm, 'i')) !== -1;
                    });
                    return {
                        count: result.data.length,
                        values: _.take(results.limit)
                    };
                });
        }
    }
};

我在控制台中遇到的错误是:

Error: [$injector:undef] Provider 'Company' must return a value from $get factory method.

2 个答案:

答案 0 :(得分:1)

在修改代码后,我得到了Girafa的回复帮助;

class Company {...}

function CompanyFactory () {
  return new Company();
}

...

app.factory('Company', CompanyFactory);

答案 1 :(得分:0)

角度出厂应注册为功能。该函数的返回值将是factory的值。

你应该用一个函数包装你的类:

class Company {...}

export function CompanyFactory () {
  return Company;
}

...

app.factory('Company', CompanyFactory);

此代码适用于需要手动创建Company类实例的情况。如果Company是单身,请将其注册为service

app.service('Company', Company);