2013-04-09 23 views
17

Ho appena iniziato ad imparare Angular.js. Come posso riscrivere il seguente codice in Angular.js?

var postData = "<RequestInfo> " 
      + "<Event>GetPersons</Event> "   
     + "</RequestInfo>"; 

    var req = new XMLHttpRequest(); 

    req.onreadystatechange = function() { 
     if (req.readyState == 4 || req.readyState == "complete") { 
      if (req.status == 200) { 
       console.log(req.responseText); 
      } 
     } 
    }; 

    try { 
     req.open('POST', 'http://samedomain.com/GetPersons', false); 
     req.send(postData); 
    } 
    catch (e) { 
     console.log(e); 
    } 

Ecco quello che ho finora -

function TestController($scope) { 
     $scope.persons = $http({ 
      url: 'http://samedomain.com/GetPersons', 
      method: "POST", 
      data: postData, 
      headers: {'Content-Type': 'application/x-www-form-urlencoded'} 
     }).success(function (data, status, headers, config) { 
       $scope.data = data; // how do pass this to $scope.persons? 
      }).error(function (data, status, headers, config) { 
       $scope.status = status; 
      }); 

} 

html

<div ng-controller="TestController">  
    <li ng-repeat="person in persons">{{person.name}}</li> 
</div> 

Am I nella direzione giusta?

risposta

41

Nella funzione corrente se si assegna $scope.persons a $http che è un oggetto promessa come $http restituisce un oggetto promessa.

Così, invece di assegnare scope.persons a $ http si dovrebbe assegnare $scope.persons all'interno del successo di $http come indicato di seguito:

function TestController($scope, $http) { 
     $http({ 
      url: 'http://samedomain.com/GetPersons', 
      method: "POST", 
      data: postData, 
      headers: {'Content-Type': 'application/x-www-form-urlencoded'} 
     }).success(function (data, status, headers, config) { 
       $scope.persons = data; // assign $scope.persons here as promise is resolved here 
      }).error(function (data, status, headers, config) { 
       $scope.status = status; 
      }); 

} 
+0

La ringrazio molto. Ha funzionato perfettamente. – tempid

+0

Grazie, ho provato tante soluzioni ma intestazioni: '{'Content-Type': 'application/x-www-form-urlencoded'}' ha fatto il trucco –

+2

Si noti che le funzioni 'success' e' error' hanno deprecato ora. – Ali

13

Ecco una variante della soluzione data dal Ajay beni. L'utilizzo del metodo quindi consente di concatenare più promesse, poiché lo quindi restituisce una nuova promessa.

function TestController($scope) { 
    $http({ 
     url: 'http://samedomain.com/GetPersons', 
     method: "POST", 
     data: postData, 
     headers: {'Content-Type': 'application/x-www-form-urlencoded'} 
    }) 
    .then(function(response) { 
      // success 
     }, 
     function(response) { // optional 
      // failed 
     } 
    ); 
} 
0

uso $ http:

AngularJS: API: $http

$http.post(url, data, [config]); 

esempio di implementazione:

$http.post('http://service.provider.com/api/endpoint', { 
     Description: 'Test Object', 
     TestType: 'PostTest' 
    }, { 
     headers { 
      'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==', 
      'Accept': 'application/json;odata=verbose' 
     } 
    } 
).then(function (result) { 
    console.log('Success'); 
    console.log(result); 
}, function(error) { 
    console.log('Error:'); 
    console.log(error); 
}); 

Consente una scomposizione: URL è un po 'ovvio, quindi saltiamo che ..

  1. dati: Questo è il contenuto del corpo della tua richiesta postino

    { 
        Description: 'Test Object', 
        TestType: 'PostTest' 
    } 
    
  2. config: Questo è dove possiamo iniettare intestazioni, gestori di eventi, il caching ... vedere AngularJS: API: $http: scroll down to config intestazioni sono la variante più comune di postino http che la gente fatica a replicare in angularJS

    { 
        headers { 
         'Authorization': 'Basic d2VudHdvcnRobWFuOkNoYW5nZV9tZQ==', 
         'Accept': 'application/json;odata=verbose' 
        } 
    } 
    
  3. risposta: il $ azioni HTTP restituiscono una promessa angolare, mi consiglia di utilizzare .then (successFunction, funzione degli errori) per processi che promettono vedere AngularJS: The Deferred API (Promises)

    .then(function (result) { 
        console.log('Success'); 
        console.log(result); 
    }, function(error) { 
        console.log('Error:'); 
        console.log(error); 
    });