Redirect the JSON response to another html page (Angular)
我最近才开始使用 Angular,我正在尝试将 http.get 的响应重定向到另一个 html 页面,即
这是我的控制器代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | app.controller("controller", function($scope, $http, $window, sharedProperties){ $scope.generate = function(){ $http.get('repositories', {params: { username : $scope.username }}). then(function mySucces(response) { $scope.error =""; sharedProperties.setData(response.data); $window.location.href = '/result.html'; }, function myError() { $scope.error ="Wrong Username"; }); } }); app.controller("resultController", function($scope, $window,sharedProperties){ $scope.names = sharedProperties.getData(); $scope.home = function() { $window.location.href = '/index.html'; } }); |
这里是
1 2 3 4 5 6 7 8 9 10 11 | app.service('sharedProperties', function() { var data; return { getData: function() { return data; }, setData: function(value) { data = value; }, } }); |
这是
1 2 3 4 5 6 | <p> <input type="text" ng-model="username" placeholder="Enter username here" required> <button ng-click="generate()">Generate</button> </p> {{ error }} |
这是我想要响应的
1 2 3 4 5 6 7 8 9 10 11 | <p><center>[wp_ad_camp_2]</center></p><p><button ng-click="home()">Home</button></p> <ul> <li ng-repeat="x in names"> {{"Name:" + x.name +", Languages:" + x.languages }} </li> </ul> |
更新
似乎两个控制器之间没有共享数据,
更新 2
我意识到重定向会重置所有数据,所以我使用
1 2 3 4 5 6 7 8 9 10 11 | app.service('sharedProperties', function() { return { getData: function() { return sessionStorage.sharedProperties; }, setData: function(value) { sessionStorage.sharedProperties = value; }, } }); |
然而
1 | "[object Object],[object Object],[object Object],[object Object],[object Object]" |
真正的价值应该是:
1 | [{"name":"git-consortium","languages":"No Language Reported"},{"name":"hello-worId","languages":"No Language Reported"},{"name":"Hello-World","languages":"No Language Reported"},{"name":"octocat.github.io","languages":"CSS JavaScript HTML"},{"name":"Spoon-Knife","languages":"CSS HTML"}] |
对此有什么想法吗?
即使我得到的响应是 json,我仍然必须使用
转换为 json
这里是保存json数据的服务:
1 2 3 4 5 6 7 8 9 10 | app.service('sharedProperties', function() { return { getData: function() { return angular.fromJson(sessionStorage.sharedProperties); }, setData: function(value) { sessionStorage.sharedProperties = angular.toJson(value); }, } }); |
所以现在即使重定向到另一个页面,我仍然可以访问数据。