Use $http in the custom service to obtain the data of the local json file. The request can be successful, but the data cannot be obtained in the controller.
When you break the point, you see that the data is empty. The page is refreshed but there is data. What is the reason?
Customized service code:
blogModule.service('blogData', ['$http', '$q',
function ($http, $q) {
var service = {
returnedData: {},
dataLoaded: {},
getData: function (forceRefresh) {
var dfd = $q.defer();
if (!service.dataLoaded.genericData || forceRefresh) {
$http.get('../app/db.json')
.then(function success(data) {
angular.copy(data.data, service.returnedData);
service.dataLoaded.genericData = true;
dfd.resolve(service.returnedData);
})
} else {
dfd.resolve(service.returnedData);
}
return dfd.promise();
},
addSomeData: function (someDataToAdd) {
$http.post('../app/db.json', someDataToAdd)
.then(function success(data) {
service.getData(true);
})
}
};
service.getData();
return service;
}
]);
Code inside controller:
blogModule.controller('blogController', ['$scope', '$routeParams', '$location', 'blogData',
function ($scope, $routeParams, $location, blogData) {
var getBlogData = blogData.returnedData;
var titles = $scope.titles = getBlogData.titles;
console.log(blogData);
console.log(titles);
}
]);
JSON data required:
{
"titles": [
{
"title": "入门笔记",
"source": "_post/入门笔记.html",
"date": "201512",
"categories": [
"笔记",
"小事记"
],
"tags": [
"笔记",
"小事记"
]
},
{
"title": "入门笔记2",
"source": "_post/入门笔记2.html",
"date": "201512",
"categories": [
"基础",
"日常"
],
"tags": [
"基础",
"日常"
]
}
]
}
The break point is console.log
After the page is refreshed, it is
Why can’t I get data from the controller? Is it because of asynchrony?
Problem with asynchronous calls
After you execute service.getData()
service.returnedData value is still empty~~~
Also, why is service.getData() called in service?
services should be called by other modules. What is the point of loading data when other modules do not need data? Is it necessary to preload?
1. The service name you wrote in the service code is requestData, but the name you wrote in the controller is blogData. I don't know if this is the reason.
2. If you use $http in a custom Service, you need to separate the $http and then parts and call them one after another in the controller code.
In other words, the controller must be written at least like this:
requestData.getData().then(callback function)
It is recommended to encapsulate the callback function part into your custom service