角度工厂获取数据

Angular Factory getdata

本文关键字:数据 获取 工厂      更新时间:2023-09-26

我正在尝试创建一个带有 Angular 的工厂.js并且 y 具有来自 GitHub API 的 JSON 结构:

[
  {
    "login": "mojombo",
    "id": 1,
    "avatar_url": "https://avatars.githubusercontent.com/u/1?v=3",
    "gravatar_id": "",
    "url": "https://api.github.com/users/mojombo",
    "html_url": "https://github.com/mojombo",
    "followers_url": "https://api.github.com/users/mojombo/followers",
    "following_url": "https://api.github.com/users/mojombo/following{/other_user}",
    "gists_url": "https://api.github.com/users/mojombo/gists{/gist_id}",
    "starred_url": "https://api.github.com/users/mojombo/starred{/owner}{/repo}",
    "subscriptions_url": "https://api.github.com/users/mojombo/subscriptions",
    "organizations_url": "https://api.github.com/users/mojombo/orgs",
    "repos_url": "https://api.github.com/users/mojombo/repos",
    "events_url": "https://api.github.com/users/mojombo/events{/privacy}",
    "received_events_url": "https://api.github.com/users/mojombo/received_events",
    "type": "User",
    "site_admin": false
  }]

我想从包含用户信息的 url 属性中获取数据,这个想法是从所有用户那里获取该数据。

这是我到目前为止出厂的代码:

angular
  .module('app')
  .factory('userFactory', function($http){
    function getData(){
      return $http.get('https://api.github.com/users');
    }
    function userData(){
      getData().success(function(data){
        return $http.get('https://api.github.com/users'+ data.url)
      }).error()
    }
    return{
      getData : getData
    }
  });

这是控制器:

angular
  .module('app')
  .controller('listUserController', function($scope, userFactory){
    $scope.users;
    userFactory.getData().success(function(data){
      $scope.users = data;
    }).error(function(error){
      console.log(error);
    })

  });

但是我可以得到数据,请你帮忙.......

Angular 将 api 响应封装在一个对象中,请尝试

userFactory.getData().success(function(response){ // response instead of data
  $scope.users = response.data; // response.data instead of data
}).error(function(error){
  console.log(error);
})

你可以在这里尝试工作PLNKR。

它确实:

$resource(user.url)

请求个人用户提供其数据

result.push(userData)

推送到结果并返回到控制器

userFactory.userData().then(function(data){
    vm.userData = data;
});

我们在这里使用 $resource,因为我们希望在结果数组中保留对数据的引用。然后,在来自服务器的响应之后,我们的结果数组将反映更改并显示在视图中。