工厂实施问题
Factory implementation issue
我正在尝试创建服务,就是这样:
(function () {
'use strict';
angular
.module('app')
.factory('appService', Service);
function Service($http) {
function getData() {
var request = new XMLHttpRequest();
request.open('GET', 'mock.json', false);
request.send(null);
return [request.status, request.response, {}];
}
return {};
}
})();
其中 mock.json
在同一文件夹中。
然后我尝试从控制器调用它:
(function () {
'use strict';
angular.module('app')
.controller('appCtrl', appCtrl);
/** @ngInject */
function appCtrl(appService) {
console.log(appService.getData());
}
})();
但是它给我一个错误:
TypeError: appService.getData is not a function
我做错了什么?
您正在返回空对象,因此您得到了预期的错误。
function Service($http) {
function getData() {
var request = new XMLHttpRequest();
request.open('GET', 'mock.json', false);
request.send(null);
return [request.status, request.response, {}];
}
//Here return the function reference of getData
return {
getData : getData
};
}
您只是缺少return Service
上具有适当属性的对象
return {
getData: getData
}
我正在尝试创建服务,就是这样:
(function () {
'use strict';
angular
.module('app')
.factory('appService', Service);
function Service($http) {
function getData() {
var request = new XMLHttpRequest();
request.open('GET', 'mock.json', false);
request.send(null);
return [request.status, request.response, {}];
}
return {};
}
})();
其中 mock.json
在同一文件夹中。
然后我尝试从控制器调用它:
(function () {
'use strict';
angular.module('app')
.controller('appCtrl', appCtrl);
/** @ngInject */
function appCtrl(appService) {
console.log(appService.getData());
}
})();
但是它给我一个错误:
TypeError: appService.getData is not a function
我做错了什么?
您正在返回空对象,因此您得到了预期的错误。
function Service($http) {
function getData() {
var request = new XMLHttpRequest();
request.open('GET', 'mock.json', false);
request.send(null);
return [request.status, request.response, {}];
}
//Here return the function reference of getData
return {
getData : getData
};
}
您只是缺少return Service
return {
getData: getData
}