The Api service can be configured by using the provider. This needs to happen in the config phase of the module in which you want to use this service.
Example
angular
.module( 'example.json' )
.config( config )
;
// @ngInject
function config( ApiProvider ) {
ApiProvider.setConfig('protocol', 'https://');
ApiProvider.setConfig('baseUrl', 'api.com/api.php');
}
These are the options you can set during the configuration phase
| Option | Type | Default | Description |
|---|---|---|---|
| debug | Boolean | false | Setting this flag to true will enable logging of all api calls |
| protocol | String | '' | Allows you to set the protocol. Examples: 'https://', 'http://', 'ftp://', 'file://' |
| baseUri | String | 'api/' | The base Uri of the api. Example: 'api.com/api.php' |
| defaultHttpMethod | String | 'GET' | The default http method off all calls. You can set this per API call by passing in the methodoption |
| parseArrayAsJson | Boolean | false | In case we need to give mixed content types. This options will parse arrays as Json inside a form-url-encoded data object. |
This is the only public function of this service. It allows you to do any pink of http call to different end points
Api.call( {
data: {
c: 'funkyFunction'
},
resolve: function( response ) {
console.log( response.data );
}
} );
| Option | Type | Default | Description |
|---|---|---|---|
| url | String | service.baseUrl + params.url | Will add this url to the base url which is set in the config phase through config.protocol and config.baseUri |
| method | String | config.defaultHttpMethod | Sets http method for this call. Examples: 'POST', 'GET', 'PUT', 'DELETE' |
| data | Object | undefined | The data that you can send with a POST or PUT request |
| resolve | Function | angular.noop | This function will be called once the call resolves. It will return http.response. |
| reject | Function | service.reject | This function will be called if the call gets rejected. It will return http.response. |
Get a local json file.
Example Code
Config
function config( ApiProvider ) {
ApiProvider.setConfig('baseUri', 'app/example/json/');
}
Controller/Service
Api.call( {
url: 'json.json',
resolve: gotJson
} );
{{JsonCtrl.result | json}}
Example Code
Config
angular
.module( 'example.api' )
.config( config )
;
// @ngInject
function config( ApiProvider ) {
ApiProvider.setConfig('protocol', 'http://');
ApiProvider.setConfig('baseUri', 'jsonplaceholder.typicode.com');
ApiProvider.setConfig('defaultHttpMethod', 'GET');
}
Controller/Service
Api.call( {
url: '/posts/1',
resolve: gotApiResult
} );
{{ApiCtrl.result | json}}