如何从角度服务工厂创建动态文件资源?

时间:2013-04-09 16:59:08

标签: javascript angularjs

可以拥有动态文件资源吗?

这是我的工厂

factory('fileResourcedc', function ($resource) {
    var FileResourcedc = $resource(
                'xml/file.json',{},
                {
                    get:{method:'GET', isArray:false}
                }
            );
    return FileResourcedc;
})  

我从这里叫它:

    var deferred = $q.defer();
    var successFn = function (result) {
        if (angular.equals(result, [])) {
            deferred.reject("Failed  because empty : " + result.message);
        }
        else {
            deferred.resolve(result);
        }
    };
    var failFn = function (result) {
       deferred.reject("Failed dataconfResponse");
    };
    fileResourcedc.get(successFn, failFn);
    return deferred.promise;

请注意,在我的工厂中,文件名是硬编码的:

'xml/file.json'

我需要创建一个文件名参数并将其传递给工厂服务。有可能吗?

事先提前

1 个答案:

答案 0 :(得分:0)

这是我的解决方案:

factory('fileResourcedc', function ($resource) {
    var FileResourcedc = $resource(
                'xml/:myFile',
                {},
                {
                    get:{method:'GET', params:{myFile:""}, isArray:false}
                }
            );
    FileResourcedc.prototype.getCatalogue = function (fileName, successCat, failCat) {
        return FileResourcedc.get({myFile:fileName}, successCat, failCat);

    };
    return new FileResourcedc;
})

呼叫:

        var deferred = $q.defer();
        var successFn = function (result) {
            if (angular.equals(result, {})) {
                deferred.reject("No catalogue");
            }
            else {
                deferred.resolve(result);
            }
        };
        var failFn = function (result) {
           deferred.reject("Failed catalogue");
        };
        fileResourcedc.getCatalogue("catalogues.json",successFn, failFn);
        return deferred.promise;

谢谢!