2016-04-11 17 views
1

Asenkronize bir HTTP hizmetine Angular'da bir geri bildirimi nasıl ayarlayabilirim böylece dizilim denetleyicide tanımlanmadan dizimi doldurabilir miyim?Anısal olmayan bir HTTP hizmetine geri dönüşü nasıl açabilirim, böylece dizilim denetleyicide tanımlanmadan dizimi doldurabilir miyim?

Benim Kod: (my updateUser.php doğru yanıt için konsolda aradılar çünkü hiçbir özel)

'use strict'; 

    var app = angular.module('app', ['ngRoute']); //create module 

    app.factory("Rest", ['$http', function($http){ //create service factory 
     var allUsers = []; //initialize empty allUsersArray 
     return{ 
      getUsers: function(doneCallback){ //getUsers function with a callback parameter 
       var getHttp = $http({ //GET request from my test.json 
        method: 'GET', 
        url: 'test.json' 
       }); 
       getHttp.then(function successCallback(response) { 
        var users = response.data; 
        for(var i = 0; i < users.people.length; i++){ 
         allUsers.push(users.people[i]); //add the objects to the allUsers array at the top 
        } 
        console.log("This is from within the SERVICE: " + allUsers[1].first); //showing that I can access the allUsers array within the service. 

        doneCallback(response.data.people); //my sad attempt to call this in the controller and still ended up being undefined. 

       }, function errorCallback(response) { 
        console.log("Error!"); 
       }); 
      } 
     } 

    }]); 

    app.controller('mainCtrl', ['$scope', 'Rest', function($scope, Rest){ 
     $scope.usersArray = []; 
     //when the get request is completed fill in the $scope.usersArray 
     $scope.addUsers = function(users){ 
      for(var i = 0; i < users.length; i++){ 
       $scope.usersArray.push(users); //trying to add the users from the SERVICE to the CONTROLLER $scope.usersArray[] 
      } 
      console.log("This is from within the CONTROLLER: " + $scope.usersArray[1].first); //showing up as undefined :(
     } 
     Rest.getUsers($scope.addUsers); 
     //$scope.getUsers = Rest.getUsers; 
    }]); 

index.html app.js

<!DOCTYPE html> 
<html lang="en" ng-app="app"> 
<head> 
    <meta charset="UTF-8"> 
    <title>Restful Test</title> 
</head> 
<body ng-controller="mainCtrl"> 
    <h1>Welcome to REST Test!</h1> 
</body> 
<script src="bower_components/jquery/dist/jquery.min.js"></script> 
<script src="bower_components/angular/angular.min.js"></script> 
<script src="bower_components/angular-route/angular-route.min.js"></script> 
<script src="app.js"></script> 
</html> 

updateUser.php

{ 
    "people": [ 
     {"first": "Edward", "last": "Smith", "age": 18, "position": "Accountant"}, 
     {"first": "Lucas", "last": "Santos", "age": 23, "position": "Programmer"}, 
     {"first": "Jeremy", "last": "Grey", "age": 27, "position": "Fire Fighter"} 
    ] 
} 

Yani sadece test amaçlı ve bu soruya uğruna olabildiğince basit kodumu tutmak çalıştı

<?php 
    $use = json_decode(file_get_contents("php://input")); 

    for($i=0; $i < count($use->users); $i++){ 
     var_dump($use->users[$i]->first . " " . $use->users[$i]->last . " is a " . $use->users[$i]->position); 
    } 
?> 

test.json.

Yaptığım benim sorunum, JSgular verimi Angular'ın $ http hizmeti GET yöntemiyle çekilmek için kullanabilmem için öncelikle denetleyicide erişilebilir olmasını sağlamalıyım; Denetleyicinin içinden istediğimi yaparım. Ancak şimdiki sorun, $ http çağrısının eşzamansız olması ve denetleyicide $ scope.usersArray'u doldurması gerekmeden JSON'u almamasıdır; bu nedenle undefined.

yüzden geri çağırma işlevi ateş önce tamamlanması için söz varsayalım $ http.then yöntemi içinde ateşler doneCallback adında bir geri çağırma işlevi yapma çalıştı. Bazı nedenlerden ötürü, Denetleyicinin içinde doldurmaya çalıştığım dizi, ne olursa olsun, henüz tanımlanmamıştır.

Siz sadece Rest hizmetinden bir söz dönebilirsiniz
+0

Eğer angularjs –

+0

Sizin ana ait $ q hizmetini kullanabilirsiniz gör Sorun, $ scope.usersArray.push (users) 'dır. Bu muhtemelen $ scope.usersArray.push (kullananlar [i]) olmalıdır, ancak daha zarif bir çözüm için aşağıdaki cevabımı görmeliyim. – Phil

cevap

2

, örneğin

app.factory("Rest", ['$http', function($http) { 
    return { 
     getUsers: function() { 
      return $http.get('test.json').then(function(response) { 
       // the return value of this promise chain... 
       return response.data.people || []; 
      }); 
     } 
    }; 
}]) 

ve denetleyici içinde

$scope.usersArray = []; 
Rest.getUsers().then(function(people) { 
    console.log(people); 

    // to push all the new "people" into the array... 
    Array.prototype.push.apply($scope.usersArray, people); 
}); 

"Merging two arrays"

+0

Tamam o zaman yolunu ve yolumu denedim ama [i] eksiktim ve ikisi de işe yaradı. Yani denedim geri arama tüm ama çalıştı ama yolunuzu en iyi şekilde gibi görünüyor Eğer yanılmıyorsam –

+0

Hey Hey, denetleyicideki kısmı anlamıyorum. .en (işlev (insanlar) {} 'o zaman nasıl İnsan parametresinin serviste iade edilen verilerim olduğunu bildiğime dair söz veriyorum? –

+0

"Rest.getUsers" öğesinden döndürülen söz, response.data.people' ile çözüldü.'Söz tamam bakın gerçekten hem yardım takdir Cevabınız için teşekkür ederim – Phil

İlgili konular