简体   繁体   中英

$http.get API in Angular JS

I'm trying to do an ng-repeat in AngularJS that pulls from the uiFaces API . This is my code at the moment. This http.get is wrapped inside my .controller :

$http.get('http://uifaces.com/api/v1/random').success(function(data){
      $scope.uifaces = data;
});

And I'm trying to repeat a list of faces with ng-repeat :

<ul>
  <li ng-repeat="face in uifaces">
      <h6>{{ face.username }}</h6>
      <img ng-src="{{ face.image_urls.normal }}">
  </li>
</ul>

But I just keep getting two blank list items. I'm very new to Angular and APIs so trying to wrap my head around why nothing is being returned. Can anyone tell me what I'm doing wrong?

Any help is appreciated. Thanks in advance!

The data provided by /random isn't a collection of multiple face s to repeat for. It's just a single Object .

{
    "username": "...",
    "image_urls": {
        "normal": "...",
        ...
    }
}

Though, as an object, you could access its properties directly.

<ul>
  <li>
    <h3>{{ uifaces.username }}</h6>
    <img ng-src="{{ uifaces.image_urls.normal }}">
  </li>
</ul>

Or, if you want to use it as a collection to repeat , you'll have to define that part yourself:

// wrap `data` in an `Array` to `repeat`
$scope.uifaces = [ data ];

Here is the result I got from that api call:

{
  "username": "jckieangel",
  "image_urls": {
    "epic": "https:\/\/s3.amazonaws.com\/uifaces\/faces\/twitter\/jckieangel\/128.jpg",
    "bigger": "https:\/\/s3.amazonaws.com\/uifaces\/faces\/twitter\/jckieangel\/73.jpg",
    "normal": "https:\/\/s3.amazonaws.com\/uifaces\/faces\/twitter\/jckieangel\/48.jpg",
    "mini": "https:\/\/s3.amazonaws.com\/uifaces\/faces\/twitter\/jckieangel\/24.jpg"
  }
}

So not sure why you are getting two blank LIs and not just one.

You'll need to strip out those backslashes in the image_urls before they will display right, so you'll probably want to add a helper method for that

  <h6>{{ face.username }}</h6>
  <img ng-src="{{ fixUrl(face.image_urls.normal) }}">

and then create fixUrl(url) in your controller

Also you'll need to either directly make it an array (or add the data to an existing one) $scope.uifaces = [data]; or remove the ng-repeat since its a single item.

don't use ng-repeat because its only one item.

<ul>
<h6>{{ face.username }}</h6>
      <img ng-src="{{ face.image_urls.normal }}">
</ul>
<ul>
  <li ng-repeat="face in uifaces">
   <h6>{{ face.username }}</h6>
   <img ng-src="face.image_urls.normal">
  </li>
</ul>

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