【问题标题】:embed json data file into angular build将 json 数据文件嵌入到角度构建中
【发布时间】:2015-10-22 19:18:26
【问题描述】:

我正在尝试构建一个使用 json 文件作为数据源的角度模块。

我可以使用 gulp 构建一组 app.js / app.css 文件,然后 bower 可以使用这些文件来创建可安装的模块,但我一直不知道如何包含/引用这个 json 文件

所以,我有一个这样定义的模块(伪代码)

(function() {
  'use strict';

  angular
    .module('myFoo', ['ngResource']);
    .service('myService',myService);

    /** @ngInject */
    function myService($resource) {
        return $resource('somefile.json');
    }
})();

我现在可以构建这个模块,通过 bower 使其可用,然后将该模块“bower install”到我的应用程序中,注入并使用它 - 不幸的是,我得到了一个

https://myServer/somefile.json404(未找到)

如何将此 json 文件嵌入/包含到可以通过这种方式引用的构建中?

如果我修改服务以直接返回数据,那么它会按预期工作。

如果没有更好的选择,我打算直接将内容注入到服务文件中。

希望有任何见解。谢谢!

【问题讨论】:

    标签: json angularjs gulp


    【解决方案1】:
    angular.module('prerequisites', ['constants']).run(function ($http, $cacheFactory, somefileConstant) {
      $cacheFactory.get('$http').put('somefile.json', somefileConstant);
    });
    

    constants 模块和somefileConstant 特别是可以用gulp-ng-constantgulp-ng-config 构建。并且prerequisites模块可以在必须请求真正的json的情况下用空模块替换/重新定义。

    angular
    .module('myFoo', ['ngResource']);
    .service('myService',myService);
    
    /** @ngInject */
    function myService($resource) {
        return $resource('somefile.json', null, { get: { cache: true } });
    }
    

    我猜get 操作是为此而设计的,但可以用针对此资源的任何其他操作替换。

    【讨论】:

      猜你喜欢
      • 2012-03-20
      • 1970-01-01
      • 2018-06-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-07-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多