an angular module for SWAPI
$ bower install ne-swapi --save
or
npm install ne-swapi --save
$ angular.module('myApp', ['ne.swapi'])
controller usage:
angular.module('myApp')
.controller('starshipsController', function($scope, swapi) {
swapi.starships.all()
.then(function(starships) {
$scope.starships = starships;
});
});
route resolve usage:
angular.module('myApp')
.config(function($routeProvider) {
$routeProvider
.when('/starships', {
templateUrl: 'starships.html',
controller: 'starshipsController',
resolve: {
starships: function(swapi) {
return swapi.starships.all();
}
}
}
});
});
ne-swapi provides one general purpose helper method:
swapi.get(url)
gets the resource(s) at the given url
and the following 5 helper methods for each of the SWAPI endpoints (films, people, planets, species, starships, vehicles):
.all()
returns a promise that resolves to all resources (not paginated)- sample:
swapi.films.all()
- sample:
.id(id)
returns a promise that resolves to a specific resource (defaults to 1)- sample:
swapi.people.id(5)
- sample:
.get()
returns a promise that resolves to the first page of resources- sample:
swapi.planets.get()
- sample:
.page(page)
returns a promise that resolves to the nth page of resources (defaults to 1)- sample:
swapi.species.page(3)
- sample:
.schema()
returns a promise that resolves to the resource schema- sample:
swapi.starships.schema()
- sample:
A wrapper for $http.get
.
swapi.get('http://swapi.co/api/people/1/')
.then(function(person) {
$scope.person = person; // {"name": "Luke Skywalker", "height": "172", ...}
});
swapi.vehicles.all()
.then(function(allVehicles) {
$scope.vehicles = allVehicles; // {"count": 39, "results": [{"name": "Sand Crawler", ...} ...] ...}
});
swapi.films.id(3)
.then(function(film) {
$scope.film = film; // {"title": "Return of the Jedi", "episode_id": 6, ...}
});
swapi.people.get()
.then(function(people) {
$scope.people = people; // {"count": 82, "next": "http://swapi.co/api/people/?page=2", ...}
});
swapi.people.page(3)
.then(function(people) {
$scope.people = people; // {"count": 82, "next": "http://swapi.co/api/people/?page=4", ...}
});
swapi.species.schema()
.then(function(speciesSchema) {
$scope.schema = speciesSchema; // {"required": ["name", "height", "mass", ...] ...}
});
since all methods return promises, you can chain calls:
swapi.films.id(2)
.then(function(film) {
return swapi.get(film.characters[0]);
})
.then(function(person) {
return swapi.get(person.vehicles[1]);
})
.then(function(vehicle) {
$scope.vehicle = vehicle;
})
.catch(function(error) {
//any error in the chain will fall through to here and skip subsequent .then calls
})