[英]Angular js controller design passing data of http post response to another controller
我是Angularjs的新手。 我對控制器的設計和數據共享有疑問。
我有第一個部分upload.html
,它使用UploadCntrl
使用$http.post
將word文檔上傳到服務器。 服務器調用封裝在uploadService
。 在服務器端,我安排了文檔中單詞列表出現的頻率,並將該信息作為對$http.post
響應返回。
回到UploadCntrl
,成功后我想直接/顯示第二個部分report.html,它使用AnalyseCntrl
以表格形式顯示分析的響應( $http.post
提到的$http.post
)。
如何使用AnalyseCntrl
在UploadCntrl
共享分析響應?
這是設計控制器的正確方法嗎?
這樣做的方法是創建一個服務並將其注入兩個控制器。
app.service("sharedService", function () {
return {
sharedObject: {data: null}
};
});
現在在每個控制器中,這樣的事情:
app.controller("myController", ["$scope", "$http", "$filter", "storageService", function($scope, $http, $filter, storageService) {
// We don't need to put it on the $scope but it makes it available to the view
$scope.shared = storageService.sharedObject;
...
// After the following line, the other controller will have access to
// storageService.sharedObject.myThing as well. Easy!
$scope.shared.myThing = "your thing";
...
在AngularJS中共享數據最好通過服務或工廠完成 。 另一種選擇是將響應local storage
在瀏覽器的local storage
中,然后在AnalyseCntrl
訪問它。
所以,在UploadCntrl
類似的UploadCntrl
:
anaylseAPI.sendToAnalyse(object).then( function (response) {
localStorage.setItem("howMany", response.amount);
});
然后訪問AnaylseCntrl
的localStorage
。
另一個解決方案是使用服
它們的行為類似於單身人士,因此您可以將它們用作數據存儲。
angular
.module( 'app', [])
.service('DataStore', DataStore);
function DataStore() {
this.amount = 0;
return function(amountOf) {
this.amount = amountOf;
};
}
現在在兩個控制器中inject
服務,並從中保存/獲取數據。
您可以編寫一個負責發送您的帖子請求的angularjs服務。 在此服務中,您可以使用變量存儲響應,並提供getter方法來檢索此變量的值。
此外,您可能希望提供一個函數,將您的文件作為參數並生成$http
請求。 只要收到服務器的響應,就會將響應值分配給變量並發送廣播。
廣播可以是這樣的
$rootScope.$broadcast('response-recieved');
您接下來要做的是在兩個控制器中注入此服務,收聽廣播事件,然后調用服務的get方法來檢索響應。
你可以這樣做:
$scope.$on('response-recieved', function() {
var myResponse = MyService.getResponse();
}
在這里,您可以找到如何使用服務的示例。 如果這有助於您,請告訴我。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.