简体   繁体   中英

Angular custom service call fails

I have been following a tutorial online on PluralSight for working with Angular, however it appears that some of the information is outdated.

I have reached a section on creating custom services and have followed the tutorial to the letter however my custom service will not work correctly.

It seems to fail when I try to call my github service, it looks like the promise fails to return correctly to the script.js .then() handler for github.getUser()

The plunk for it is here http://plnkr.co/edit/8vy6ZMpUJBfEOQ3qFoKk

Can someone please tell me what I am missing here?

If you want just to get it to work, here's how to fix it:

Your second option is to add a return to your $http on the service, like this:

var getUser = function(username) {
  return $http.get("https://api.github.com/users/" + username)
    .then(function(response) {
      return response.data;
    });
};

Note that you only forgot the first "return" before the $http. The rest was working well

A better way to solve that would be to not resolve your promise inside the service. That way you get a thin service and can manage your data as you like within your controller.

So I changed your getUser to this:

var getUser = function(username) {
  return $http.get("https://api.github.com/users/" + username);
};

This way it returns the entire promise from $http . Since I removed your "wrapper" I need to modify your onUserComplete () too:

var onUserComplete = function(result) {
  $scope.user = result.data;
  github.getRepos($scope.user).then(onRepos, onError);
};

Here is the working plunker: http://plnkr.co/edit/8abkaU08fCzFreA5APz1?p=info

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM