最近Angularを使い始めました。http:getの応答を別のhtmlページresult.html
にリダイレクトしようとしています。私は、データを共有するためのサービスを使用:ここでJSONレスポンスを別のhtmlページにリダイレクトする(Angular)
は私のコントローラのコードである:ここで
app.service('sharedProperties', function() {
var data;
return {
getData: function() {
return data;
},
setData: function(value) {
data = value;
},
}
});
がindex.html
体である:
<div ng-app="App" ng-controller="controller">
<p>
<input type="text" ng-model="username" placeholder="Enter username here" required>
<button ng-click="generate()">Generate</button>
</p>
{{ error }}
</div>
ここ
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';
}
});
はservices.js
コードがありますそして、ここには私が応答したいと思うresult.html
がありますO:
<div ng-app="App" ng-controller="resultController">
<p><button ng-click="home()">Home</button></p>
<ul>
<li ng-repeat="x in names">
{{ "Name: " + x.name + ", Languages: " + x.languages }}
</li>
</ul>
</div>
controller
のでresultController
ページが結果が示されていないresult.html
にリダイレクトしかし後に、それを使用することができsharedProperties
介して応答データを設定します。
UPDATE
データが2つのコントローラ間で共有されていないと思われる、console.log
はundefined
を示しています。それは2つの異なるHTMLファイルのためですか?またはredirect
のためですか?私はリダイレクトすべてのデータをリセットすることに気づいたので、私はサービスのsessionStorate
を使用
UPDATE 2
:ただし
app.service('sharedProperties', function() {
return {
getData: function() {
return sessionStorage.sharedProperties;
},
setData: function(value) {
sessionStorage.sharedProperties = value;
},
}
});
console.log
代わりにJSONの値を示し、それは示しています。
"[object Object],[object Object],[object Object],[object Object],[object Object]"
実際の値は次のようになります。
[{"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.jsを読んで学んでください。質問が表示されたらここに尋ねます。 :) –
リダイレクトルートが正しく定義されていることを確認してください。デフォルトのケースにリダイレクトされることがあります。 – lalitpatadiya
(1)コントローラの両方に同じ名前を付ける(2)2つのコントローラ間でデータを共有したいので、どちらかのサービス/ファクトリを使用してください(3)$ window.location.href = 'result。 html '; result.htmlにリダイレクトされ、一度下の式$ scope.names = response.dataにリダイレクトされます。実行されません。 – shreyansh