Redirect the JSON response to another html page (Angular)
我最近才开始使用 Angular,我正在尝试将 http.get 的响应重定向到另一个 html 页面,即 result.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){ |
这里是 services.js 代码:
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; }, } }); |
这是 index.html 正文:
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 }} |
这是我想要响应的 result.html:
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”> |
controller通过sharedProperties设置响应数据,所以resultController可以使用,但是页面重定向到result.html后结果不显示。
更新
似乎两个控制器之间没有共享数据,console.log显示undefined。是因为2个不同的html文件吗?还是因为 redirect?
更新 2
我意识到重定向会重置所有数据,所以我使用 sessionStorate 作为服务:
1
2 3 4 5 6 7 8 9 10 11 |
app.service(‘sharedProperties’, function() {
return { |
然而 console.log 不是显示 json 的值,而是显示:
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”}]
|
对此有什么想法吗?
- 您的angular项目实施完全错误。请先阅读并了解 angular.js。那么如果有任何问题出现在这里问。 :)
- 请确保您的重定向路由定义正确,有时它会重定向到默认情况..?
- (1) 您为两个控制器提供相同的名称。(2) 您想在两个控制器之间共享数据,因此请使用服务/工厂,阅读它。(3) $window.location.href = ‘result.html ‘;将重定向到 result.html 并一旦重定向以下表达式 $scope.names = response.data;不会被执行。
- 但即使你想用这种方式实现,你也可以使用 $rootScope.names=response.data 然后重定向到 result.html,只是一个技巧,但它可能会产生不好的后果。
- 感谢您的回复@shreyansh
- @shreyansh 我用你的建议更新了这个问题,你能告诉我它有什么问题吗?
即使我得到的响应是 json,我仍然必须使用 angular.toJson().
转换为 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); }, } }); |
所以现在即使重定向到另一个页面,我仍然可以访问数据。
来源:https://www.codenong.com/36263046/