gpt4 book ai didi

javascript - 为什么我在 angularjs 中没有遇到函数错误?

转载 作者:行者123 更新时间:2023-12-03 04:06:47 24 4
gpt4 key购买 nike

我正在按照我在 Stormpath 找到的教程进行操作.
我试图了解 AngularJS 的工作原理,但我无法运行编辑功能( Controller )。我总是收到类型错误:

TypeError: SearchService.fetch is not a function

在其调用堆栈中,它引用指向这行代码的 EditController:

SearchService.fetch($stateParams.id, function (response) {

这是EditController的完整代码:

(function () {
'use strict';

angular
.module('myApp')
.controller('EditController', EditController);

EditController.$inject = ['SearchService', '$stateParams'];

function EditController(SearchService, $stateParams) {
var vm = this;

SearchService.fetch($stateParams.id, function (response) {
vm.person = response;
});
}


})();

但是我不知道这里出了什么问题。我正在尝试将此代码与 SearchController 的代码进行比较 - 请参见下文,

(function () {
'use strict';

angular
.module('myApp')
.controller('SearchController', SearchController);

SearchController.$inject = ['SearchService'];

function SearchController(SearchService) {
var vm = this;

vm.search = function(){
SearchService.query(vm.term, function (response) {
var results = response.filter(function (item) {
return JSON.stringify(item).toLowerCase().includes(vm.term.toLowerCase());
});
vm.searchResults = results;
});
}
}
})();

这是SearchService的代码:

(function () {
'use strict';

angular
.module('myApp')
.factory('SearchService', SearchService);

SearchService.$inject = ['$resource'];

function SearchService($resource) {
return $resource('/api/search/people.json');
}

SearchService.fetch = function (id, callback) {
Search.query(function (response) {
var results = response.filter(function (item) {
return item.id === parseInt(id);
});
return callback(results[0]);
});
};

})();

任何建议都值得赞赏,我已经花了几天时间尝试各种事情。

最佳答案

让你的搜索服务像这样......

The service factory function generates the single object or function that represents the service to the rest of the application. The object or function returned by the service is injected into any component (controller, service, filter or directive) that specifies a dependency on the service

https://docs.angularjs.org/guide/services

(function () {
'use strict';

angular.module('myApp')
.factory('SearchService', SearchService);

SearchService.$inject = ['$resource'];

function SearchService($resource, $http) {
var service = {};
service.url = $resource('/api/search/people.json');
var req = {
method: 'GET',
url: 'http://example.com',
headers: {
'Content-Type': undefined
},
data: { test: 'test' }

}

service.fetch = function (id, callback) {
// $http.get('yourapi.json').then() you can try like this also
return $http(req).then(function (response) {
var results = response.filter(function (item) {
return item.id === parseInt(id);
});
return callback(results[0]);
});
};
return service;
}
})();

关于javascript - 为什么我在 angularjs 中没有遇到函数错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44514672/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com