[英]Read JSON with Angular, undefined service
I am trying to read a JSON data from a file using angular factory and service. 我正在尝试使用角度工厂和服务从文件读取JSON数据。 But Angular can't see my defined service.
但是Angular无法看到我定义的服务。 Here is my factory:
这是我的工厂:
//jsonService.js
angular.module('jsonService', ['ngResource'])
.factory('JsonService', function($resource) {
alert($resource)
return $resource('example.json',{}, {
getData: {method:'GET', isArray: false}
});
});
And my controller: 而我的控制器:
//app.js
'use strict';
angular.module('myApp', [
'ngRoute',
'myApp.view1',
'myApp.view2',
'myApp.version',
'jsonService'
]).config(['$routeProvider', function($routeProvider) {
$routeProvider.otherwise({redirectTo: '/view1'});
}]).
controller('mainController', ['JsonService', function($scope, JsonService){
JsonService.getData(function(data) {
console.log("Test");
$scope.length = data.length;
})}]);
And I get: 我得到:
"Error: JsonService is undefined"
“错误:JsonService未定义”
You're injecting 'JsonService'
as the first parameter of your function, but you are using the JsonService as the 2nd parameter of your function. 您将
'JsonService'
作为函数的第一个参数注入,但是您将JsonService用作函数的第二个参数。
Should be ['JsonService', '$scope', function($scope, JsonService){
or if $scope
not needed then ['JsonService', function(JsonService){
应
['JsonService', '$scope', function($scope, JsonService){
或如果$scope
不需要然后['JsonService', function(JsonService){
app.js中的这一行应该看起来像
controller('mainController', ['$scope','JsonService', function($scope, JsonService){
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.