2017-01-29 10 views
0

Я только начинаю с Node.js, и я пытаюсь сделать pokedex с pokeAPI, у меня проблема с использованием запросов $ q и $ http. Когда я пытаюсь сделать вызов api, он возвращает «ReferenceError: getPokes не определен». При попытке выяснить, что вызывает это, я обнаружил, что putPokes на переменной вызывает ошибку, чтобы перейти к «ReferenceError: response not defined». Может быть, мне это не нужно, и я не понимаю логику. В любом случае, я знаю, что мне не хватает какой-то важной логики, может быть, что-то в моем контроллере? Любая помощь очень ценится!

EDIT: Я так обнаружил, что если я удалить pokeName из this.willCollectThemAll он возвращает запросы $ HTTP с, где pokeName в запросе и показывает неопределенными (http://pokeapi.co/api/v2/pokemon/ + pokeName Который имеет смысл, поскольку это не получение прошло. в, но он показывает на $ HTTP завершения, в отличие от которой, если я ставлю в pokeName в this.willCollectThemAll, где он говорит, что функция getPokes неопределен, который где я тупик

SERVICE:.

// INITIALIZE SERVICE 
// ============================================================ 
angular.module("app").service("pokeService", function($http, $q, $timeout) { 
// ============================================================ 
this.willCollectThemAll = function(pokeName) { 
    var deferred = $q.defer(); 
    var pokemon = false; 
    var morePokemon = false; 
    var pokemonCaught = false; 
    var allPokemonCaught = false; 


    getPokes = function(pokeName) { 
     $http({ 
      url: 'http://pokeapi.co/api/v2/pokemon/' + pokeName, 
      method: 'GET' 
     }).then(function(response) { 
      console.log('service:', response); 
      pokemon = response.data; 
      pokemonCaught = True; 
      checkAllPokemon(); 

     }) 
    } 
    getMorePokes = function(pokeName) { 
     $http({ 
      url: 'http://pokeapi.co/api/v2/pokemon-species/' + pokeName, 
      method: 'GET' 
     }).then(function(response) { 
      console.log('service:', response); 
      morePokemon = response.data; 
      allPokemonCaught = true; 
      checkAllPokemon(); 

     }) 
    } 

    function checkAllPokemon() { 
     if (pokemonCaught && allPokemonCaught) { 
      if (pokemon && morePokemon) { 
       deferred.resolve(true); 
      } else { 
       deferred.reject(true) 
      } 
     } 
    } 
    console.log('service', response) 
    getPokes(); 
    getMorePokes(); 
    return deferred.promise; 

} 

});

Контроллер:

// INITILIZE CONTROLLER 
// ============================================================ 
angular.module("app").controller("pokeCtrl", function($scope, $q, pokeService) { 

// VARIABLES 
// ============================================================ 


// FUNCTIONS 
// ============================================================ 
$scope.willCollectThemAll = function() { 

    pokeService.willCollectThemAll($scope.pokeName.toLowerCase()) 
     .then(function(response) { 
      console.log(pokeService, response); 
      $scope.pokeData = response; 
     }) 
} 

});

ответ

0

Я видел пару проблем с вашим кодом, номер один - вы должны вернуть свои $ http-вызовы, которые вам не хватает. Попробуйте следующее в вашей службе.

this.willCollectThemAll = function(pokeName) { 
    var deferred = $q.defer(); 
    var pokemon = false; 
    var morePokemon = false; 
    var pokemonCaught = false; 
    var allPokemonCaught = false; 


    getPokes = function(pokeName) { 
     return $http({ 
      url: 'http://pokeapi.co/api/v2/pokemon/' + pokeName, 
      method: 'GET' 
     }).then(function(response) { 
      return response.data; 
     }) 
    } 
    getMorePokes = function(pokeName) { 
     return $http({ 
      url: 'http://pokeapi.co/api/v2/pokemon-species/' + pokeName, 
      method: 'GET' 
     }).then(function(response) { 
      return response.data; 
     }) 
    } 

    function checkAllPokemon() { 
     if (pokemonCaught && allPokemonCaught) { 
      if (pokemon && morePokemon) { 
       deferred.resolve(true); 
      } else { 
       deferred.reject(true) 
      } 
     } 
    } 

    getPokes().then(function (data){ 
     pokemon = data; 
     pokemonCaught = true; 
     checkAllPokemon(); 
    }); 

    getMorePokes().then(function (data){ 
     morePokemon = response.data; 
     allPokemonCaught = true; 
     checkAllPokemon(); 
    }); 
    return deferred.promise; 
} 
+0

Я попытался, как Вы предложили, к сожалению, она возвращает эту ошибку ReferenceError: ответ не определен на Object.willCollectThemAll (pokeService.js: 50) в ChildScope $ scope.willCollectThemAll (pokeCtrl.js.: 12) –

0

Эта штука выглядит так, будто у нее есть работа с Charizard.

Еще раз я думаю, что @AliBaig имеет право на это, но сама прикладная логика неисправна. Я думаю, вы хотите объединить обещания, чтобы вы получили больше покемонов, если вы не получите все в первый раз.

Вот вам быстрый код вашего кода.

this.willCollectThemAll = function(pokeName) { 
    // $q.when() is a nice shortcut for this logic and creates a new promise each time. 
    //var deferred = $q.defer(); 
    var pokemon; // prolly better to make these empty arrays then check for length instead of checking for boolean value. 
    var morePokemon; 
    var pokemonCaught = false; 
    var allPokemonCaught = false; 

    // getPokes returns a promise. 
    var getPokes = function(pokeName) { 
     return $http({ 
      url: 'http://pokeapi.co/api/v2/pokemon/' + pokeName, 
      method: 'GET' 
     }).then(function(response) { 
      return response.data; 
     }) 
    } 
    // getMorePokes also returns a promise. 
    var getMorePokes = function(pokeName) { 
     return $http({ 
      url: 'http://pokeapi.co/api/v2/pokemon-species/' + pokeName, 
      method: 'GET' 
     }).then(function(response) { 
      return response.data; 
     }) 
    } 

    // If you resolve the promise here you will be trying to resolve the same promise multiple times. 
    function checkAllPokemon() { 
     if (pokemonCaught && allPokemonCaught) { 
      if (pokemon && morePokemon) { 
       //deferred.resolve(true); 
       return true; 
      } else { 
       //deferred.reject(true); 
       return false; 
      } 
     } 
    } 

    // Have getPokes() return a promise and give this promis back to the controller. 
    return getPokes().then(function (data){ 
     pokemon = data; 
     pokemonCaught = true; 
     // In either case here we're gonna return a promise. 
     if (!checkAllPokemon()) { 
      return getMorePokes().then(function(data) { 
       morePokemon = response.data; 
       allPokemonCaught = true; 
       //returning pokemon with ES6 syntax cuz I'm lazy. 
       return checkAllPokemon() ? $q.when([...pokeman, ...morePokemon]) : $q.reject('Did not getem all. :('); 

      }); 
     } else { 
      // If we already have the pokemon don't bother chaining again. 
      return $q.when([...pokeman, ...morePokemon]); 
     } 
    }); 
} 

Примечание: существует множество ошибок, которые должны быть должным образом учтены.