3

我被困在一些問題上,實際上我是在解決問題,問題是不能獲得響應的頭(如CORS問題),通過使用header和transformRequest來克服,如下所示碼。之後,我得到了web服務數據,但是在一個控制器中使用了$ rootcope,它使第二種方法(API)的某些數據的id在另一個控制器中用於放置第三個api來獲取數據,然後我只用了一分鐘它會拋出錯誤:無法讀取第三個API中字段爲null的屬性'公司數據'。當我使用$ rootScope.Test.companies [0] .companyname這是存儲數據,並且對於所有API如主鍵都是唯一的。

var request = $http({ 
     method: "post", 
     url: "http://app.xyz/xyzapp/public/user/login", 
     headers: {'Content-Type': 'application/x-www-form-urlencoded'}, 
     transformRequest: function(obj) { 
      var str = []; 

      str.push(encodeURIComponent('email_id') + "=" + encodeURIComponent('[email protected]')); 
      str.push(encodeURIComponent('password') + "=" + encodeURIComponent('[email protected]')); 
      return str.join("&"); 
     },    

    }); 

    request.success(function(response) { 

     console.log("Hiiiii::::"+JSON.stringify(response,status)); 
     if (response.status=="success"){ 


      $rootScope.Test1=response.user_id; 

      var request1 = $http({ 
       method: "post", 
       url: "http://app.xyz/xyzapp/public/company/getUserCompanyList", 
       headers: {'Content-Type': 'application/x-www-form-urlencoded'}, 
       transformRequest: function(obj) { 
       var str = []; 

       str.push(encodeURIComponent('user_id') + "=" + encodeURIComponent(response.user_id)); 
       // str.push(encodeURIComponent('password') + "=" + encodeURIComponent('[email protected]')); 
       return str.join("&"); 
       }   

      }); 
// getCompany 
      request1.success(function(response) { 

       console.log("Hiiiii::::"+JSON.stringify(response,status)+" "+response.companies.length+":Length"); 
       if (response.status=="success"){ 
       // alert(1); 
       $state.go('tabdash'); 
       $rootScope.Test = response; 


       }    
      }); 

所以,請告訴我如何,我現在用另一種API,它會得到父母的$ rootscope日期使用一個控制器到另一個數據。 請讓我知道,如果有人知道這件事或任何

感謝

回答

1

是的,你可以使用一個控制器的變量使用兩種方法

  1. 創建服務在它們之間通信的另一個控制器內。 。
  2. 使用$ rootScope $廣播

示例代碼

angular.module('myservice', []).service('msgBus', function() { 
     this.serviceValue= {}; 

    }]); 
}); 

,並用它在控制器這樣的:

控制器1

angular.module('myservice', []).controller('ctrl1',function($scope, msgBus) { 
    $scope.sendmsg = function() { 
     msgBus.serviceValue='Hello'; 
    } 
}); 

控制器2

angular.module('myservice', []).controller('ctrl2',function($scope, msgBus) { 
$scope.checkValue(){ 
alert(msgBus.serviceValue); 
} 
}); 
+0

如果我嵌套$ http,並且想要將嵌套的一個數據返回給控制器,那麼我會怎麼做?請告訴我。 –

+0

你需要的是'$ q.all'。參考:http://stackoverflow.com/questions/17027196/angularjs-multiple-http-get-request/17027441#17027441 –

+0

$ http({method:'GET',url:'/ api-one-url',data :{email:email,pwd:pwd})然後(函數(apiOneData){http://方法:'GET',url:'/ api-two-url',data:{userid:userid}} )。然後(函數(apiTwoData){//我想保存在陣列響應於一個以上的控制器使用 \t \t的console.log(apiOneData,apiTwoData); \t}); }); –