1.目的:期望该远程数据(json.json)需要重复利用,希望只请求一次json.json数据,可以在多个控制器中反复使用
2.问题:路由每跳转一次,就会重新请求一次'json.json'
3.代码如下
<script>
angular.module("myApp",[])
.factory("$remoteData",['$http',function($http){
return $http.get("../json/json.json").then(function(response){
//获取 远程数据 服务
//目的:期望该远程数据(json.json)需要重复利用,希望只请求一次json.json数据,可以在多个控制器中反复使用
//问题:路由每跳转一次,就会重新请求一次'json.json'
console.log(response.data);
var myData = "";
return myData = response.data;
})
}])
.factory("$localData",function(){
return {"name":"wenwu","age":"26"};
})
.controller("FirstController",function($scope,$remoteData,$localData){
//远程请求的数据 --获取失败(如果这里能够获取json.json的数据,应该就成功了)
$scope.remoteData = $remoteData;
console.log('$scope.remoteData',$scope.remoteData);//返回 $scope.remoteData d {$$state: Object}
console.log('$scope.remoteData.$$state.value',$scope.remoteData.$$state.value);//返回undefined
//本地制作的数据 -- 获取成功
$scope.localData = $localData;
console.log($scope.localData);//返回 Object {name: "wenwu", age: "26"}
})
</script>
You can try this:
Use it like this in the controller:
Use service singleton, hang the object reference on the service object, and fetch this object directly later
Angular has the root scope $rootScope. You can persist the data common to each controller to the root scope and obtain it only once through appropriate methods.