簡體   English   中英

Angular js控制器設計將http post響應的數據傳遞給另一個控制器

[英]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 )。

如何使用AnalyseCntrlUploadCntrl共享分析響應?

這是設計控制器的正確方法嗎?

這樣做的方法是創建一個服務並將其注入兩個控制器。

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);
});

然后訪問AnaylseCntrllocalStorage

另一個解決方案是使用服

它們的行為類似於單身人士,因此您可以將它們用作數據存儲。

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM