{"id":14973328,"url":"https://github.com/2muchcoffeecom/ng2-restangular","last_synced_at":"2025-10-26T23:30:36.899Z","repository":{"id":57179771,"uuid":"88485078","full_name":"2muchcoffeecom/ng2-restangular","owner":"2muchcoffeecom","description":"Restangular for Angular 2 (RENAMED DUE TO ANGULAR SEMVER)","archived":false,"fork":false,"pushed_at":"2017-06-08T17:03:52.000Z","size":1374,"stargazers_count":27,"open_issues_count":4,"forks_count":7,"subscribers_count":4,"default_branch":"master","last_synced_at":"2025-10-17T00:25:00.996Z","etag":null,"topics":["angular","angular-2","angular2","api","error-handling","fetch","fetch-api","http","observable","reactive","request","response","rest","rest-api","rest-client","restangular","restangular-methods","restful","restful-api","rxjs"],"latest_commit_sha":null,"homepage":"http://ngx-restangular.com","language":"JavaScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"mit","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/2muchcoffeecom.png","metadata":{"files":{"readme":"README.md","changelog":"CHANGELOG.md","contributing":null,"funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null}},"created_at":"2017-04-17T07:51:51.000Z","updated_at":"2024-12-11T14:34:39.000Z","dependencies_parsed_at":"2022-09-26T16:51:09.937Z","dependency_job_id":null,"html_url":"https://github.com/2muchcoffeecom/ng2-restangular","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/2muchcoffeecom/ng2-restangular","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/2muchcoffeecom%2Fng2-restangular","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/2muchcoffeecom%2Fng2-restangular/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/2muchcoffeecom%2Fng2-restangular/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/2muchcoffeecom%2Fng2-restangular/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/2muchcoffeecom","download_url":"https://codeload.github.com/2muchcoffeecom/ng2-restangular/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/2muchcoffeecom%2Fng2-restangular/sbom","scorecard":{"id":3048,"data":{"date":"2025-08-11","repo":{"name":"github.com/2muchcoffeecom/ng2-restangular","commit":"ab17f0d3ba8d4d20c924540a552ce8218a53577e"},"scorecard":{"version":"v5.2.1-40-gf6ed084d","commit":"f6ed084d17c9236477efd66e5b258b9d4cc7b389"},"score":3,"checks":[{"name":"Token-Permissions","score":-1,"reason":"No tokens found","details":null,"documentation":{"short":"Determines if the project's workflows follow the principle of least privilege.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#token-permissions"}},{"name":"Maintained","score":0,"reason":"0 commit(s) and 0 issue activity found in the last 90 days -- score normalized to 0","details":null,"documentation":{"short":"Determines if the project is \"actively maintained\".","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#maintained"}},{"name":"Packaging","score":-1,"reason":"packaging workflow not detected","details":["Warn: no GitHub/GitLab publishing workflow detected."],"documentation":{"short":"Determines if the project is published as a package that others can easily download, install, easily update, and uninstall.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#packaging"}},{"name":"Code-Review","score":0,"reason":"Found 0/30 approved changesets -- score normalized to 0","details":null,"documentation":{"short":"Determines if the project requires human code review before pull requests (aka merge requests) are merged.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#code-review"}},{"name":"Dangerous-Workflow","score":-1,"reason":"no workflows found","details":null,"documentation":{"short":"Determines if the project's GitHub Action workflows avoid dangerous patterns.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#dangerous-workflow"}},{"name":"SAST","score":0,"reason":"no SAST tool detected","details":["Warn: no pull requests merged into dev branch"],"documentation":{"short":"Determines if the project uses static code analysis.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#sast"}},{"name":"Binary-Artifacts","score":10,"reason":"no binaries found in the repo","details":null,"documentation":{"short":"Determines if the project has generated executable (binary) artifacts in the source repository.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#binary-artifacts"}},{"name":"CII-Best-Practices","score":0,"reason":"no effort to earn an OpenSSF best practices badge detected","details":null,"documentation":{"short":"Determines if the project has an OpenSSF (formerly CII) Best Practices Badge.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#cii-best-practices"}},{"name":"Pinned-Dependencies","score":-1,"reason":"no dependencies found","details":null,"documentation":{"short":"Determines if the project has declared and pinned the dependencies of its build process.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#pinned-dependencies"}},{"name":"Security-Policy","score":0,"reason":"security policy file not detected","details":["Warn: no security policy file detected","Warn: no security file to analyze","Warn: no security file to analyze","Warn: no security file to analyze"],"documentation":{"short":"Determines if the project has published a security policy.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#security-policy"}},{"name":"Vulnerabilities","score":10,"reason":"0 existing vulnerabilities detected","details":null,"documentation":{"short":"Determines if the project has open, known unfixed vulnerabilities.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#vulnerabilities"}},{"name":"License","score":10,"reason":"license file detected","details":["Info: project has a license file: LICENSE:0","Info: FSF or OSI recognized license: MIT License: LICENSE:0"],"documentation":{"short":"Determines if the project has defined a license.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#license"}},{"name":"Signed-Releases","score":-1,"reason":"no releases found","details":null,"documentation":{"short":"Determines if the project cryptographically signs release artifacts.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#signed-releases"}},{"name":"Fuzzing","score":0,"reason":"project is not fuzzed","details":["Warn: no fuzzer integrations found"],"documentation":{"short":"Determines if the project uses fuzzing.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#fuzzing"}},{"name":"Branch-Protection","score":0,"reason":"branch protection not enabled on development/release branches","details":["Warn: branch protection not enabled for branch 'master'"],"documentation":{"short":"Determines if the default and release branches are protected with GitHub's branch protection settings.","url":"https://github.com/ossf/scorecard/blob/f6ed084d17c9236477efd66e5b258b9d4cc7b389/docs/checks.md#branch-protection"}}]},"last_synced_at":"2025-08-14T12:58:10.545Z","repository_id":57179771,"created_at":"2025-08-14T12:58:10.545Z","updated_at":"2025-08-14T12:58:10.545Z"},"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":281092762,"owners_count":26442440,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","status":"online","status_checked_at":"2025-10-26T02:00:06.575Z","response_time":61,"last_error":null,"robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":true,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["angular","angular-2","angular2","api","error-handling","fetch","fetch-api","http","observable","reactive","request","response","rest","rest-api","rest-client","restangular","restangular-methods","restful","restful-api","rxjs"],"created_at":"2024-09-24T13:48:33.774Z","updated_at":"2025-10-26T23:30:36.525Z","avatar_url":"https://github.com/2muchcoffeecom.png","language":"JavaScript","readme":"# Current stage ([Team of maintainers](https://2muchcoffee.com/) had to RENAME project due to Angular SemVer, please use [ngx-restangular](https://github.com/2muchcoffeecom/ngx-restangular/) instead)\n\nThis project was renamed from **ng2-restangular** to [ngx-restangular](https://github.com/2muchcoffeecom/ngx-restangular/) due to implementation of Semantic Versioning by Angular Core Team. NPM name also changed, you can install actual version of project with ``npm install ngx-restangular``, as example.\n\n# Ng2-Restangular\n\nThis project is the follow-up of the [Restangular](https://github.com/mgonto/restangular/). Ng2-Restangular is an Angular 2 service that simplifies common GET, POST, DELETE, and UPDATE requests with a minimum of client code.\nIt's a perfect fit for any WebApp that consumes data from a RESTful API.\n\n# Demo\n\nLive Demo on Plunkr [Hero App](http://embed.plnkr.co/qozGPV2HowzmtKbC9a54/).\nYou can also check post about using ng2-restangular with [restdb.io](https://restdb.io/) service in [simple TODO Application](http://blog.2muchcoffee.com/angular_todo_application_with_ng2-restangular_and_restdb-io/)\n\n# Table of contents\n\n- [How do I add this to my project in angular 2?](#how-do-i-add-this-to-my-project-in-angular-2)\n- [How do I add this to my project in angular 4?](#how-do-i-add-this-to-my-project-in-angular-4)\n- [Dependencies](#dependencies)\n- [Starter Guide](#starter-guide)\n  - [Quick configuration for Lazy Readers](#quick-configuration-for-lazy-readers)\n  - [Using Restangular](#using-restangular)\n    - [Creating Main Restangular object](#creating-main-restangular-object)\n    - [Lets Code with Observables!](#lets-code-with-observables)\n    - [Here is Example of code with using promises!](#here-is-example-of-code-with-using-promises)\n  - [Configuring Restangular](#configuring-restangular)\n    - [Properties](#properties)\n      - [withConfig](#withconfig)\n      - [setBaseUrl](#setbaseurl)\n      - [setExtraFields](#setextrafields)\n      - [setParentless](#setparentless)\n      - [addElementTransformer](#addelementtransformer)\n      - [setTransformOnlyServerElements](#settransformonlyserverelements)\n      - [setOnElemRestangularized](#setonelemrestangularized)\n      - [addResponseInterceptor](#addresponseinterceptor)\n      - [addFullRequestInterceptor](#addfullrequestinterceptor)\n      - [addErrorInterceptor](#adderrorinterceptor)\n      - [setRestangularFields](#setrestangularfields)\n      - [setMethodOverriders](#setmethodoverriders)\n      - [setDefaultRequestParams](#setdefaultrequestparams)\n      - [setFullResponse](#setfullresponse)\n      - [setDefaultHeaders](#setdefaultheaders)\n      - [setRequestSuffix](#setrequestsuffix)\n      - [setUseCannonicalId](#setusecannonicalid)\n      - [setPlainByDefault](#setplainbydefault)\n      - [setEncodeIds](#setencodeids)\n    - [Accessing configuration](#accessing-configuration)\n    - [How to configure them globally](#how-to-configure-them-globally)\n      - [Configuring in the AppModule](#configuring-in-the-appmodule)\n      - [Configuring in the AppModule with Dependency Injection applied](#configuring-in-the-appmodule-with-dependency-injection-applied)\n    - [How to create a Restangular service with a different configuration from the global one](#how-to-create-a-restangular-service-with-a-different-configuration-from-the-global-one)\n    - [Decoupled Restangular Service](#decoupled-restangular-service)\n  - [Methods description](#methods-description)\n    - [Restangular methods](#restangular-methods)\n    - [Element methods](#element-methods)\n    - [Collection methods](#collection-methods)\n    - [Custom methods](#custom-methods)\n  - [Copying elements](#copying-elements)\n  - [Using values directly in templates with Observables](#using-values-directly-in-templates-with-observables)\n  - [URL Building](#url-building)\n  - [Creating new Restangular Methods](#creating-new-restangular-methods)\n  - [Adding Custom Methods to Collections](#adding-custom-methods-to-collections)\n    - [Example:](#example)\n  - [Adding Custom Methods to Models](#adding-custom-methods-to-models)\n    - [Example:](#example-1)\n- [FAQ](#faq)\n    - [How can I handle errors?](#how-can-i-handle-errors)\n   - [I need to send Authorization token in EVERY Restangular request, how can I do this?](#i-need-to-send-authorization-token-in-every-restangular-request-how-can-i-do-this)\n    - [I need to send one header in EVERY Restangular request, how can I do this?](#i-need-to-send-one-header-in-every-restangular-request-how-can-i-do-this)\n    - [How can I send a delete WITHOUT a body?](#how-can-i-send-a-delete-without-a-body)\n    - [I use Mongo and the ID of the elements is _id not id as the default. Therefore requests are sent to undefined routes](#i-use-mongo-and-the-id-of-the-elements-is-_id-not-id-as-the-default-therefore-requests-are-sent-to-undefined-routes)\n    - [What if each of my models has a different ID name like CustomerID for Customer](#what-if-each-of-my-models-has-a-different-id-name-like-customerid-for-customer)\n    - [How can I send files in my request using Restangular?](#how-can-i-send-files-in-my-request-using-restangular)\n    - [How do I handle CRUD operations in a List returned by Restangular?](#how-do-i-handle-crud-operations-in-a-list-returned-by-restangular)\n    - [Removing an element from a collection, keeping the collection restangularized](#removing-an-element-from-a-collection-keeping-the-collection-restangularized)\n    - [How can I access the unrestangularized element as well as the restangularized one?](#how-can-i-access-the-unrestangularized-element-as-well-as-the-restangularized-one)\n    - [How can add withCredentials params to requests?](#how-can-add-withcredentials-params-to-requests)\n- [Server Frameworks](#server-frameworks)\n- [License](#license)\n\n**[Back to top](#table-of-contents)**\n\n# How do I add this to my project in angular 2?\n\nYou can download this by:\n\n* Using npm and running `npm install ng2-restangular`\n\n**[Back to top](#table-of-contents)**\n\n# How do I add this to my project in angular 4?\n\nYou can download this by:\n\n* Using npm and running `npm install ng2-restangular@beta`\n\n**[Back to top](#table-of-contents)**\n\n# Dependencies\n\nRestangular depends on Angular2 and Lodash.\n\n**[Back to top](#table-of-contents)**\n\n# Starter Guide\n\n## Quick Configuration (For Lazy Readers)\nThis is all you need to start using all the basic Restangular features.\n\n````javascript\nimport { NgModule } from '@angular/core';\nimport { AppComponent } from './app.component';\nimport { RestangularModule, Restangular } from 'ng2-restangular';\n\n// Function for settting the default restangular configuration\nexport function RestangularConfigFactory (RestangularProvider) {\n  RestangularProvider.setBaseUrl('http://api.restng2.local/v1');\n  RestangularProvider.setDefaultHeaders({'Authorization': 'Bearer UDXPx-Xko0w4BRKajozCVy20X11MRZs1'});\n}\n\n// AppModule is the main entry point into Angular2 bootstraping process\n@NgModule({\n  bootstrap: [ AppComponent ],\n  declarations: [\n    AppComponent,\n  ],\n  imports: [\n    // Importing RestangularModule and making default configs for restanglar\n    RestangularModule.forRoot(RestangularConfigFactory),\n  ]\n})\nexport class AppModule {\n}\n\n// later in code ...\n\n@Component({\n  ...\n})\nexport class OtherComponent {\n  constructor(private restangular: Restangular) {\n  }\n\n  ngOnInit() {\n    // GET http://api.test.local/v1/users/2/accounts\n    this.restangular.one('users', 2).all('accounts').getList();\n  }\n````\n**[Back to top](#table-of-contents)**\n\n## Using Restangular\n\n### Creating Main Restangular object\n\nThere are 3 ways of creating a main Restangular object.\nThe first one and most common one is by stating the main route of all requests.\nThe second one is by stating the main route and object of all requests.\n\n````javascript\n// Only stating main route\nRestangular.all('accounts')\n\n// Stating main object\nRestangular.one('accounts', 1234)\n\n// Gets a list of all of those accounts\nRestangular.several('accounts', 1234, 123, 12345);\n````\n\n**[Back to top](#table-of-contents)**\n\n### Lets Code with Observables!\n\nNow that we have our main Object let's start playing with it.\n\n````javascript\n// AppModule is the main entry point into Angular2 bootstraping process\n@NgModule({\n  bootstrap: [ AppComponent ],\n  declarations: [\n    AppComponent,\n  ],\n  imports: [\n    // Importing RestangularModule\n    RestangularModule,\n  ]\n})\nexport class AppModule {\n}\n\n@Component({\n  ...\n})\nexport class OtherComponent {\n  allAccounts;\n  accounts;\n  account;\n  \n  constructor(private restangular: Restangular) {\n  }\n  \n  ngOnInit() {\n    // First way of creating a this.restangular object. Just saying the base URL\n    let baseAccounts = this.restangular.all('accounts');\n    \n    // This will query /accounts and return a observable.\n    baseAccounts.getList().subscribe(accounts =\u003e {\n      this.allAccounts = accounts;\n    });\n    \n    \n    let newAccount = {name: \"Gonto's account\"};\n    \n    // POST /accounts\n    baseAccounts.post(newAccount);\n    \n    // GET to http://www.google.com/ You set the URL in this case\n    this.restangular.allUrl('googlers', 'http://www.google.com/').getList();\n    \n    // GET to http://www.google.com/1 You set the URL in this case\n    this.restangular.oneUrl('googlers', 'http://www.google.com/1').get();\n    \n    // You can do RequestLess \"connections\" if you need as well\n    \n    // Just ONE GET to /accounts/123/buildings/456\n    this.restangular.one('accounts', 123).one('buildings', 456).get();\n    \n    // Just ONE GET to /accounts/123/buildings\n    this.restangular.one('accounts', 123).getList('buildings');\n    \n    // Here we use Observables\n    // GET /accounts\n    let baseAccounts$ = baseAccounts.getList().subscribe(accounts =\u003e {\n      // Here we can continue fetching the tree :).\n      \n      let firstAccount = accounts[0];\n      // This will query /accounts/123/buildings considering 123 is the id of the firstAccount\n      let buildings = firstAccount.getList(\"buildings\");\n      \n      // GET /accounts/123/places?query=param with request header: x-user:mgonto\n      let loggedInPlaces = firstAccount.getList(\"places\", {query: 'param'}, {'x-user': 'mgonto'});\n      \n      // This is a regular JS object, we can change anything we want :)\n      firstAccount.name = \"Gonto\";\n      \n      // If we wanted to keep the original as it is, we can copy it to a new element\n      let editFirstAccount = this.restangular.copy(firstAccount);\n      editFirstAccount.name = \"New Name\";\n      \n      \n      // PUT /accounts/123. The name of this account will be changed from now on\n      firstAccount.put();\n      editFirstAccount.put();\n      \n      // PUT /accounts/123. Save will do POST or PUT accordingly\n      firstAccount.save();\n      \n      // DELETE /accounts/123 We don't have first account anymore :(\n      firstAccount.remove();\n      \n    }, () =\u003e {\n      alert(\"Oops error from server :(\");\n    });\n    \n    \n    // Get first account\n    let firstAccount$ = baseAccounts$.map(accounts =\u003e accounts[0]);\n    \n    \n    // POST /accounts/123/buildings with MyBuilding information\n    firstAccount$.switchMap(firstAccount =\u003e {\n      var myBuilding = {\n        name: \"Gonto's Building\",\n        place: \"Argentina\"\n      };\n      \n      return firstAccount.post(\"Buildings\", myBuilding)\n    })\n    .subscribe(() =\u003e {\n      console.log(\"Object saved OK\");\n    }, () =\u003e {\n      console.log(\"There was an error saving\");\n    });\n    \n    \n    // GET /accounts/123/users?query=params\n    firstAccount$.switchMap(firstAccount =\u003e {\n      var myBuilding = {\n        name: \"Gonto's Building\",\n        place: \"Argentina\"\n      };\n    \n      return firstAccount.getList(\"users\", {query: 'params'});\n    })\n    .subscribe((users) =\u003e {\n      // Instead of posting nested element, a collection can post to itself\n      // POST /accounts/123/users\n      users.post({userName: 'unknown'});\n    \n      // Custom methods are available now :).\n      // GET /accounts/123/users/messages?param=myParam\n      users.customGET(\"messages\", {param: \"myParam\"});\n    \n      var firstUser = users[0];\n    \n      // GET /accounts/123/users/456. Just in case we want to update one user :)\n      let userFromServer = firstUser.get();\n    \n      // ALL http methods are available :)\n      // HEAD /accounts/123/users/456\n      firstUser.head()\n    }, () =\u003e {\n      console.log(\"There was an error saving\");\n    });\n    \n    \n    // Second way of creating this.restangular object. URL and ID :)\n    var account = this.restangular.one(\"accounts\", 123);\n    \n    // GET /accounts/123?single=true\n    this.account = account.get({single: true});\n    \n    // POST /accounts/123/messages?param=myParam with the body of name: \"My Message\"\n    account.customPOST({name: \"My Message\"}, \"messages\", {param: \"myParam\"}, {})\n  }\n}\n````\n\n**[Back to top](#table-of-contents)**\n\n### Here is Example of code with using promises!\n\n\n````javascript\n@Component({\n  ...\n})\nexport class OtherComponent {\n  allAccounts;\n  accounts;\n  account;\n  \n  constructor(private restangular: Restangular) {\n  }\n  \n  ngOnInit() {\n    \n    // First way of creating a this.restangular object. Just saying the base URL\n    let baseAccounts = this.restangular.all('accounts');\n  \n    // This will query /accounts and return a promise.\n    baseAccounts.getList().toPromise().then(function(accounts) {\n      this.allAccounts = accounts;\n    });\n  \n    var newAccount = {name: \"Gonto's account\"};\n  \n    // POST /accounts\n    baseAccounts.post(newAccount);\n  \n    // GET to http://www.google.com/ You set the URL in this case\n    this.restangular.allUrl('googlers', 'http://www.google.com/').getList();\n  \n    // GET to http://www.google.com/1 You set the URL in this case\n    this.restangular.oneUrl('googlers', 'http://www.google.com/1').get();\n  \n    // You can do RequestLess \"connections\" if you need as well\n  \n    // Just ONE GET to /accounts/123/buildings/456\n    this.restangular.one('accounts', 123).one('buildings', 456).get();\n  \n    // Just ONE GET to /accounts/123/buildings\n    this.restangular.one('accounts', 123).getList('buildings');\n  \n    // Here we use Promises then\n    // GET /accounts\n    baseAccounts.getList().toPromise().then(function (accounts) {\n      // Here we can continue fetching the tree :).\n    \n      var firstAccount = accounts[0];\n      // This will query /accounts/123/buildings considering 123 is the id of the firstAccount\n      this.buildings = firstAccount.getList(\"buildings\");\n    \n      // GET /accounts/123/places?query=param with request header: x-user:mgonto\n      this.loggedInPlaces = firstAccount.getList(\"places\", {query: 'param'}, {'x-user': 'mgonto'});\n    \n      // This is a regular JS object, we can change anything we want :)\n      firstAccount.name = \"Gonto\";\n    \n      // If we wanted to keep the original as it is, we can copy it to a new element\n      var editFirstAccount = this.restangular.copy(firstAccount);\n      editFirstAccount.name = \"New Name\";\n    \n    \n      // PUT /accounts/123. The name of this account will be changed from now on\n      firstAccount.put();\n      editFirstAccount.put();\n    \n      // PUT /accounts/123. Save will do POST or PUT accordingly\n      firstAccount.save();\n    \n      // DELETE /accounts/123 We don't have first account anymore :(\n      firstAccount.remove();\n    \n      var myBuilding = {\n        name: \"Gonto's Building\",\n        place: \"Argentina\"\n      };\n    \n      // POST /accounts/123/buildings with MyBuilding information\n      firstAccount.post(\"Buildings\", myBuilding).toPromise().then(function() {\n        console.log(\"Object saved OK\");\n      }, function() {\n        console.log(\"There was an error saving\");\n      });\n    \n      // GET /accounts/123/users?query=params\n      firstAccount.getList(\"users\", {query: 'params'}).toPromise().then(function(users) {\n        // Instead of posting nested element, a collection can post to itself\n        // POST /accounts/123/users\n        users.post({userName: 'unknown'});\n      \n        // Custom methods are available now :).\n        // GET /accounts/123/users/messages?param=myParam\n        users.customGET(\"messages\", {param: \"myParam\"});\n      \n        var firstUser = users[0];\n      \n        // GET /accounts/123/users/456. Just in case we want to update one user :)\n        this.userFromServer = firstUser.get();\n      \n        // ALL http methods are available :)\n        // HEAD /accounts/123/users/456\n        firstUser.head()\n      \n      });\n    \n    }, function errorCallback() {\n      alert(\"Oops error from server :(\");\n    });\n  \n    // Second way of creating this.restangular object. URL and ID :)\n    var account = this.restangular.one(\"accounts\", 123);\n  \n    // GET /accounts/123?single=true\n    this.account = account.get({single: true});\n  \n    // POST /accounts/123/messages?param=myParam with the body of name: \"My Message\"\n    account.customPOST({name: \"My Message\"}, \"messages\", {param: \"myParam\"}, {})\n  }\n}\n````\n\n**[Back to top](#table-of-contents)**\n\n\n## Configuring Restangular\n\n### Properties\nRestangular comes with defaults for all of its properties but you can configure them. **So, if you don't need to configure something, there's no need to add the configuration.**\nYou can set all these configurations in **[RestangularModule](#how-to-configure-them-globally) to change the global configuration**, you can also **use the [withConfig](#how-to-create-a-restangular-service-with-a-different-configuration-from-the-global-one) method in Restangular service to create a new Restangular service with some scoped configuration** or **use [withConfig](#withconfig) in component to make specified Restangular**  \n\n#### withConfig\nYou can configure Restangular \"withConfig\" like in example below, you can also configure them globally **[RestangularModule](#how-to-configure-them-globally) or in service with [withConfig](#how-to-create-a-restangular-service-with-a-different-configuration-from-the-global-one)\n \n ````javascript\n// Function for settting the default restangular configuration\nexport function RestangularConfigFactory (RestangularProvider) {\n  RestangularProvider.setBaseUrl('http://www.google.com');\n}\n\n@NgModule({\n  bootstrap: [ AppComponent ],\n  declarations: [\n    AppComponent,\n  ],\n  imports: [\n    // Global configuration\n    RestangularModule.forRoot(RestangularConfigFactory),\n  ]\n})\nexport class AppModule {}\n// Let's use it in the component\n@Component({\n  ...\n})\nexport class OtherComponent {\n  constructor(private restangular: Restangular) {}\n\n  ngOnInit() {\n    restangular.withConfig((RestangularConfigurer) =\u003e {\n      RestangularConfigurer.setBaseUrl('http://www.bing.com');\n    }).all('users').getList()\n  }\n};\n ````\n\n#### setBaseUrl\nThe base URL for all calls to your API. For example if your URL for fetching accounts is http://example.com/api/v1/accounts, then your baseUrl is `/api/v1`. The default baseUrl is an empty string which resolves to the same url that Angular2 is running, but you can also set an absolute url like `http://api.example.com/api/v1` if you need to set another domain.\n\n#### setExtraFields\nThese are the fields that you want to save from your parent resources if you need to display them. By default this is an Empty Array which will suit most cases\n\n#### setParentless\nUse this property to control whether Restangularized elements to have a parent or not. So, for example if you get an account and then get a nested list of buildings, you may want the buildings URL to be simple `/buildings/123` instead of `/accounts/123/buildings/123`. This property lets you do that.\n\nThis method accepts 1 parameter, it could be:\n\n* Boolean: Specifies if all elements should be parentless or not\n* Array: Specifies the routes (types) of all elements that should be parentless. For example `['buildings']`\n\n#### addElementTransformer\nThis is a hook. After each element has been \"restangularized\" (Added the new methods from Restangular), the corresponding transformer will be called if it fits.\n\nThis should be used to add your own methods / functions to entities of certain types.\n\nYou can add as many element transformers as you want. The signature of this method can be one of the following:\n\n* **addElementTransformer(route, transformer)**: Transformer is called with all elements that have been restangularized, no matter if they're collections or not.\n\n* **addElementTransformer(route, isCollection, transformer)**: Transformer is called with all elements that have been restangularized and match the specification regarding if it's a collection or not (true | false)\n\n#### setTransformOnlyServerElements\nThis sets whether transformers will be run for local objects and not by objects returned by the server. This is by default true but can be changed to false if needed (Most people won't need this).\n\n\n#### setOnElemRestangularized\nThis is a hook. After each element has been \"restangularized\" (Added the new methods from Restangular), this will be called. It means that if you receive a list of objects in one call, this method will be called first for the collection and then for each element of the collection.\n\n**I favor the usage of `addElementTransformer` instead of `onElemRestangularized` whenever possible as the implementation is much cleaner.**\n\n\nThis callback is a function that has 4 parameters:\n\n* **elem**: The element that has just been restangularized. Can be a collection or a single element.\n* **isCollection**: Boolean indicating if this is a collection or a single element.\n* **what**: The model that is being modified. This is the \"path\" of this resource. For example `buildings`\n* **Restangular**: The instanced service to use any of its methods\n\nThis can be used together with `addRestangularMethod` (Explained later) to add custom methods to an element\n\n````javascript\nservice.setOnElemRestangularized((element, isCollection, what, Restangular) =\u003e {\n  element.newField = \"newField\";\n  return element;\n});\n````\n\n#### addResponseInterceptor\nThe responseInterceptor is called after we get each response from the server. It's a function that receives this arguments:\n\n* **data**: The data received got from the server\n* **operation**: The operation made. It'll be the HTTP method used except for a `GET` which returns a list of element which will return `getList` so that you can distinguish them.\n* **what**: The model that's being requested. It can be for example: `accounts`, `buildings`, etc.\n* **url**: The relative URL being requested. For example: `/api/v1/accounts/123`\n* **response**: Full server response including headers\n\nSome of the use cases of the responseInterceptor are handling wrapped responses and enhancing response elements with more methods among others.\n\nThe responseInterceptor must return the restangularized data element.\n\n````javascript\n RestangularProvider.addResponseInterceptor((data, operation, what, url, response)=\u003e {\n       return data;\n     });\n });\n````\n\n#### addFullRequestInterceptor\nThis adds a new fullRequestInterceptor. The fullRequestInterceptor is similar to the `requestInterceptor` but more powerful. It lets you change the element, the request parameters and the headers as well.\n\nIt's a function that receives the same as the `requestInterceptor` plus the headers and the query parameters (in that order).\n\nIt can return an object with any (or all) of following properties:\n* **headers**: The headers to send\n* **params**: The request parameters to send\n* **element**: The element to send\n\n````javascript\nRestangularProvider.addFullRequestInterceptor((element, operation, path, url, headers, params)=\u003e {\n   return {\n     params: Object.assign({}, params, {sort:\"name\"}),\n     headers: headers,\n     element: element\n   }\n });\n````\nIf a property isn't returned, the one sent is used.\n\n#### addErrorInterceptor\nThe errorInterceptor is called whenever there's an error. It's a function that receives the response, subject and the Restangular-response handler as parameters.\n\nThe errorInterceptor function, whenever it returns false, prevents the observable linked to a Restangular request to be executed. All other return values (besides false) are ignored and the observable follows the usual path, eventually reaching the success or error hooks.\n\nThe refreshAccesstoken function must return observable. It`s function that will be done before repeating the request, there you can make some actions. In switchMap you might do some transformations to request.\n````javascript\n// Function for settting the default restangular configuration\nexport function RestangularConfigFactory (RestangularProvider, authService) {\n  RestangularProvider.setBaseUrl('http://api.test.com/v1');\n    \n  // This function must return observable\n  var refreshAccesstoken = function () {\n    // Here you can make action before repeated request\n    return authService.functionForTokenUpdate();\n  };\n  \n  RestangularProvider.addErrorInterceptor((response, subject, responseHandler) =\u003e {\n    if (response.status === 403) {\n\n      refreshAccesstoken()\n      .switchMap(refreshAccesstokenResponse =\u003e {\n        //If you want to change request or make with it some actions and give the request to the repeatRequest func.\n        //Or you can live it empty and request will be the same.\n        \n        // update Authorization header\n        response.request.headers.set('Authorization', 'Bearer ' + refreshAccesstokenResponse)\n        \n        return response.repeatRequest(response.request);\n      })\n      .subscribe(\n        res =\u003e responseHandler(res),\n        err =\u003e subject.error(err)\n      );\n      \n      return false; // error handled\n    }\n    return true; // error not handled\n  });\n}\n \n// AppModule is the main entry point into Angular2 bootstraping process\n@NgModule({\n  bootstrap: [ AppComponent ],\n  imports: [ \n    // Importing RestangularModule and making default configs for restanglar\n    RestangularModule.forRoot([authService], RestangularConfigFactory),\n  ],\n})\n````\n\n#### setRestangularFields\n\nRestangular required 3 fields for every \"Restangularized\" element. These are:\n\n* id: Id of the element. Default: id\n* route: Name of the route of this element. Default: route\n* parentResource: The reference to the parent resource. Default: parentResource\n* restangularCollection: A boolean indicating if this is a collection or an element. Default: restangularCollection\n* cannonicalId: If available, the path to the cannonical ID to use. Useful for PK changes\n* etag: Where to save the ETag received from the server. Defaults to `restangularEtag`\n* selfLink: The path to the property that has the URL to this item. If your REST API doesn't return a URL to an item, you can just leave it blank. Defaults to `href`\n\nAlso all of Restangular methods and functions are configurable through restangularFields property.\nAll of these fields except for `id` and `selfLink` are handled by Restangular, so most of the time you won't change them. You can configure the name of the property that will be binded to all of this fields by setting restangularFields property.\n\n#### setMethodOverriders\n\nYou can now Override HTTP Methods. You can set here the array of methods to override. All those methods will be sent as POST and Restangular will add an X-HTTP-Method-Override header with the real HTTP method we wanted to do.\n\n````javascript\nRestangularProvider.setMethodOverriders([\"Get\",\"Put\"]);\n````\n\n#### setDefaultRequestParams\n\nYou can set default Query parameters to be sent with every request and every method.\n\nAdditionally, if you want to configure request params per method, you can use `requestParams` configuration similar to `$http`. For example `RestangularProvider.requestParams.get = {single: true}`.\n\nSupported method to configure are: remove, get, post, put, common (all)\n\n````javascript\n// set params for multiple methods at once\nRestangularProvider.setDefaultRequestParams(['remove', 'post'], {confirm: true});\n\n// set only for get method\nRestangularProvider.setDefaultRequestParams('get', {limit: 10});\n\n// or for all supported request methods\nRestangularProvider.setDefaultRequestParams({apikey: \"secret key\"});\n````\n\n#### setFullResponse\n\nYou can set fullResponse to true to get the whole response every time you do any request. The full response has the restangularized data in the `data` field, and also has the headers and config sent. By default, it's set to false. Please note that in order for Restangular to access custom HTTP headers, your server must respond having the `Access-Control-Expose-Headers:` set.\n\n````javascript\n// set params for multiple methods at once\nRestangularProvider.setFullResponse(true);\n````\n\nOr set it per service\n````javascript\n// Restangular factory that uses setFullResponse\nexport const REST_FUL_RESPONSE = new OpaqueToken('RestFulResponse');\nexport function RestFulResponseFactory(restangular: Restangular) {\n  return restangular.withConfig((RestangularConfigurer) =\u003e {\n    RestangularConfigurer.setFullResponse(true);\n  });\n}\n\n\n// Configure factory in AppModule module\n// AppModule is the main entry point into Angular2 bootstraping process\n@NgModule({\n  bootstrap: [ AppComponent ],\n  declarations: [\n    AppComponent,\n  ],\n  imports: [RestangularModule],\n  providers: [\n    { provide: REST_FUL_RESPONSE, useFactory:  RestFulResponseFactory, deps: [Restangular] }\n  ]\n})\nexport class AppModule {}\n\n\n// Let's use it in the component\n@Component({\n  ...\n})\nexport class OtherComponent {\n  users;\n  \n  constructor(@Inject(REST_FUL_RESPONSE) public restFulResponse) {\n  }\n  \n  ngOnInit() {\n    this.restFulResponse.all('users').getList().subscribe( response =\u003e {\n      this.users = response.data;\n      console.log(response.headers);\n    });\n  }\n}\n````\n\n#### setDefaultHeaders\n\nYou can set default Headers to be sent with every request. Send format: {header_name: header_value}\n````javascript\nimport { NgModule } from '@angular/core';\nimport { RestangularModule, Restangular } from 'ng2-restangular';\n\n// Function for settting the default restangular configuration\nexport function RestangularConfigFactory (RestangularProvider) {\n  RestangularProvider.setDefaultHeaders({'Authorization': 'Bearer UDXPx-Xko0w4BRKajozCVy20X11MRZs1'});\n}\n\n// AppModule is the main entry point into Angular2 bootstraping process\n@NgModule({\n  ...\n  imports: [\n    // Importing RestangularModule and making default configs for restanglar\n    RestangularModule.forRoot(RestangularConfigFactory),\n  ]\n})\nexport class AppModule {\n}\n````\n\n#### setRequestSuffix\n\nIf all of your requests require to send some suffix to work, you can set it here. For example, if you need to send the format like `/users/123.json` you can add that `.json` to the suffix using the `setRequestSuffix` method\n\n#### setUseCannonicalId\n\nYou can set this to either `true` or `false`. By default it's false. If set to true, then the cannonical ID from the element will be used for URL creation (in DELETE, PUT, POST, etc.). What this means is that if you change the ID of the element and then you do a put, if you set this to true, it'll use the \"old\" ID which was received from the server. If set to false, it'll use the new ID assigned to the element.\n\n#### setPlainByDefault\n\nYou can set this to `true` or `false`. By default it's false. If set to true, data retrieved will be returned with no embed methods from restangular.\n\n#### setEncodeIds\n\nYou can set here if you want to URL Encode IDs or not. By default, it's true.\n\n### Accessing configuration\n\nYou can also access the configuration via `RestangularModule` and `Restangular.provider` via the `configuration` property if you don't want to use the setters. Check it out:\n\n````js\nRestangularProvider.configuration.requestSuffix = '/';\n````\n\n**[Back to top](#table-of-contents)**\n\n### How to configure them globally\n\nYou can configure this in either the `AppModule`.\n\n#### Configuring in the `AppModule`\n\n````javascript\nimport { RestangularModule } from 'ng2-restangular';\n\n// Function for settting the default restangular configuration\nexport function RestangularConfigFactory (RestangularProvider) {\n  RestangularProvider.setBaseUrl('http://api.restng2.local/v1');\n  RestangularProvider.setDefaultHeaders({'Authorization': 'Bearer UDXPx-Xko0w4BRKajozCVy20X11MRZs1'});\n}\n\n// AppModule is the main entry point into Angular2 bootstraping process\n@NgModule({\n  bootstrap: [ AppComponent ],\n  declarations: [\n    AppComponent,\n  ],\n  imports: [\n    RestangularModule.forRoot(RestangularConfigFactory),\n  ]\n})\nexport class AppModule {\n}\n````\n\n**[Back to top](#table-of-contents)**\n\n\n#### Configuring in the `AppModule` with Dependency Injection applied\n\n````javascript\nimport { RestangularModule } from 'ng2-restangular';\n\n// Function for settting the default restangular configuration\nexport function RestangularConfigFactory (RestangularProvider, http) {\n  RestangularProvider.setBaseUrl('http://api.restng2.local/v1');\n  RestangularProvider.setDefaultHeaders({'Authorization': 'Bearer UDXPx-Xko0w4BRKajozCVy20X11MRZs1'});\n  \n  // Example of using Http service inside global config restangular\n  RestangularProvider.addElementTransformer('me', true, ()=\u003e{\n    return http.get('http://api.test.com/v1/users/2', {});\n  });\n}\n\n// AppModule is the main entry point into Angular2 bootstraping process\n@NgModule({\n  bootstrap: [ AppComponent ],\n  declarations: [\n    AppComponent,\n  ],\n  imports: [\n    RestangularModule.forRoot([Http], RestangularConfigFactory),\n  ]\n})\nexport class AppModule {\n}\n````\n\n**[Back to top](#table-of-contents)**\n\n### How to create a Restangular service with a different configuration from the global one\nLet's assume that for most requests you need some configuration (The global one), and for just a bunch of methods you need another configuration. In that case, you'll need to create another Restangular service with this particular configuration. This scoped configuration will inherit all defaults from the global one. Let's see how.\n\n````javascript\n// Function for settting the default restangular configuration\nexport function RestangularConfigFactory (RestangularProvider) {\n  RestangularProvider.setBaseUrl('http://www.google.com');\n}\n\n//Restangular service that uses Bing\nexport const RESTANGULAR_BING = new OpaqueToken('RestangularBing');\nexport function RestangularBingFactory(restangular: Restangular) {\n  return restangular.withConfig((RestangularConfigurer) =\u003e {\n     RestangularConfigurer.setBaseUrl('http://www.bing.com');\n   });\n}\n\n\n// AppModule is the main entry point into Angular2 bootstraping process\n@NgModule({\n  bootstrap: [ AppComponent ],\n  declarations: [\n    AppComponent,\n  ],\n  imports: [\n    // Global configuration\n    RestangularModule.forRoot(RestangularConfigFactory),\n  ],\n  providers: [\n    { provide: RESTANGULAR_BING, useFactory:  RestangularBingFactory, deps: [Restangular] }\n  ]\n})\nexport class AppModule {}\n\n\n// Let's use it in the component\n@Component({\n  ...\n})\nexport class OtherComponent {\n  constructor(\n    @Inject(Restangular) public Restangular,\n    @Inject(RESTANGULAR_BING) public RestangularBing\n  ) {}\n\n  ngOnInit() {\n    // GET to http://www.google.com/users\n    // Uses global configuration\n    Restangular.all('users').getList()\n  \n    // GET to http://www.bing.com/users\n    // Uses Bing configuration which is based on Global one, therefore .json is added.\n    RestangularBing.all('users').getList()\n  }\n};\n````\n\n**[Back to top](#table-of-contents)**\n\n### Decoupled Restangular Service\n\nThere're some times where you want to use Restangular but you don't want to expose Restangular object anywhere. For those cases, you can actually use the `service` feature of Restangular.\n\nLet's see how it works:\n\n````js\n// Restangular factory that uses Users\nexport const USER_REST = new OpaqueToken('UserRest');\nexport function UserRestFactory(restangular: Restangular) {\n  return restangular.service('users');\n}\n\n\n// AppModule is the main entry point into Angular2 bootstraping process\n@NgModule({\n  bootstrap: [ AppComponent ],\n  declarations: [\n    AppComponent,\n  ],\n  imports: [RestangularModule],\n  providers: [\n    { provide: USER_REST, useFactory:  UserRestFactory, deps: [Restangular] } // Configurating our factory\n  ]\n})\nexport class AppModule {\n}\n\n\n// Let's use it in the component\nexport class OtherComponent {\n  constructor(@Inject(USER_REST) public User) {\n    Users.one(2).get() // GET to /users/2\n    Users.post({data}) // POST to /users\n    \n    // GET to /users\n    Users.getList().subscribe( users =\u003e {\n      var user = users[0]; // user === {id: 1, name: \"Tonto\"}\n      user.name = \"Gonto\";\n      // PUT to /users/1\n      user.put();\n    })\n  }\n}\n````\n\nWe can also use Nested RESTful resources with this:\n\n````js\nvar Cars = Restangular.service('cars', Restangular.one('users', 1));\n\nCars.getList() // GET to /users/1/cars\n````\n\n**[Back to top](#table-of-contents)**\n\n## Methods description\n\nThere are 3 sets of methods. Collections have some methods and elements have others. There are are also some common methods for all of them\n\n### Restangular methods\nThese are the methods that can be called on the Restangular object.\n* **one(route, id)**: This will create a new Restangular object that is just a pointer to one element with the route `route` and the specified id.\n* **all(route)**: This will create a new Restangular object that is just a pointer to a list of elements for the specified path.\n* **oneUrl(route, url)**: This will create a new Restangular object that is just a pointer to one element with the specified URL.\n* **allUrl(route, url)**: This creates a Restangular object that is just a pointer to a list at the specified URL.\n* **copy(fromElement)**: This will create a copy of the from element so that we can modify the copied one.\n* **restangularizeElement(parent, element, route, queryParams)**: Restangularizes a new element\n* **restangularizeCollection(parent, element, route, queryParams)**: Restangularizes a new collection\n\n**[Back to top](#table-of-contents)**\n\n### Element methods\n* **get([queryParams, headers])**: Gets the element. Query params and headers are optionals\n* **getList(subElement, [queryParams, headers])**: Gets a nested resource. subElement is mandatory. **It's a string with the name of the nested resource (and URL)**. For example `buildings`\n* **put([queryParams, headers])**: Does a put to the current element\n* **post(subElement, elementToPost, [queryParams, headers])**: Does a POST and creates a subElement. Subelement is mandatory and is the nested resource. Element to post is the object to post to the server\n* **remove([queryParams, headers])**: Does a DELETE. By default, `remove` sends a request with an empty object, which may cause problems with some servers or browsers. [This](https://github.com/mgonto/restangular/issues/193) shows how to configure RESTangular to have no payload.\n* **head([queryParams, headers])**: Does a HEAD\n* **trace([queryParams, headers])**: Does a TRACE\n* **options([queryParams, headers])**: Does a OPTIONS\n* **patch(object, [queryParams, headers])**: Does a PATCH\n* **one(route, id)**: Used for RequestLess connections and URL Building. See section below.\n* **all(route)**: Used for RequestLess connections and URL Building. See section below.\n* **several(route, ids*)**: Used for RequestLess connections and URL Building. See section below.\n* **oneUrl(route, url)**: This will create a new Restangular object that is just a pointer to one element with the specified URL.\n* **allUrl(route, url)**: This creates a Restangular object that is just a pointer to a list at the specified URL.\n* **getRestangularUrl()**: Gets the URL of the current object.\n* **getRequestedUrl()**: Gets the real URL the current object was requested with (incl. GET parameters). Will equal getRestangularUrl() when no parameters were used, before calling `get()`, or when using on a nested child.\n* **getParentList()**: Gets the parent list to which it belongs (if any)\n* **clone()**: Copies the element. It's an alias to calling `Restangular.copy(elem)`.\n* **plain()**: Returns the plain element received from the server without any of the enhanced methods from Restangular. It's an alias to calling `Restangular.stripRestangular(elem)`\n* **save**: Calling save will determine whether to do PUT or POST accordingly\n\n**[Back to top](#table-of-contents)**\n\n### Collection methods\n* **getList([queryParams, headers]): Gets itself again (Remember this is a collection)**.\n* **get(id): Gets one item from the collection by id**.\n* **post(elementToPost, [queryParams, headers])**: Creates a new element of this collection.\n* **head([queryParams, headers])**: Does a HEAD\n* **trace: ([queryParams, headers])**: Does a TRACE\n* **options: ([queryParams, headers])**: Does a OPTIONS\n* **patch(object, [queryParams, headers])**: Does a PATCH\n* **remove([queryParams, headers])**: Does a DELETE. By default, `remove` sends a request with an empty object, which may cause problems with some servers or browsers. [This](https://github.com/mgonto/restangular/issues/193) shows how to configure RESTangular to have no payload.\n* **putElement(index, params, headers)**: Puts the element on the required index and returns a observable of the updated new array\n````js\nRestangular.all('users').getList()\n.subscribe( users =\u003e {\n  users.putElement(2, {'name': 'new name'});\n});\n````\n* **getRestangularUrl()**: Gets the URL of the current object.\n* **getRequestedUrl()**: Gets the real URL the current object was requested with (incl. GET parameters). Will equal getRestangularUrl() when no parameters were used, before calling `getList()`, or when using on a nested child.\n* **one(route, id)**: Used for RequestLess connections and URL Building. See section below.\n* **all(route)**: Used for RequestLess connections and URL Building. See section below.\n* **several(route, ids*)**: Used for RequestLess connections and URL Building. See section below.\n* **oneUrl(route, url)**: This will create a new Restangular object that is just a pointer to one element with the specified URL.\n* **allUrl(route, url)**: This creates a Restangular object that is just a pointer to a list at the specified URL.\n* **clone()**: Copies the collection. It's an alias to calling `Restangular.copy(collection)`.\n\n**[Back to top](#table-of-contents)**\n\n### Custom methods\n* **customGET(path, [params, headers])**: Does a GET to the specific path. Optionally you can set params and headers.\n* **customGETLIST(path, [params, headers])**: Does a GET to the specific path. **In this case, you expect to get an array, not a single element**. Optionally you can set params and headers.\n* **customDELETE(path, [params, headers])**: Does a DELETE to the specific path. Optionally you can set params and headers.\n* **customPOST([elem, path, params, headers])**: Does a POST to the specific path. Optionally you can set params and headers and elem. Elem is the element to post. If it's not set, it's assumed that it's the element itself from which you're calling this function.\n* **customPUT([elem, path, params, headers])**: Does a PUT to the specific path. Optionally you can set params and headers and elem. Elem is the element to post. If it's not set, it's assumed that it's the element itself from which you're calling this function.\n* **customPATCH([elem, path, params, headers])**: Does a PATCH to the specific path. Accepts the same arguments as customPUT.\n* **customOperation(operation, path, [params, headers, elem])**: This does a custom operation to the path that we specify. This method is actually used from all the others in this subsection. Operation can be one of: get, post, put, remove, head, options, patch, trace\n* **addRestangularMethod(name, operation, [path, params, headers, elem])**: This will add a new restangular method to this object with the name `name` to the operation and path specified (or current path otherwise). There's a section on how to do this later.\n\nLet's see an example of this:\n\n````javascript\n// GET /accounts/123/messages\nRestangular.one(\"accounts\", 123).customGET(\"messages\")\n\n// GET /accounts/messages?param=param2\nRestangular.all(\"accounts\").customGET(\"messages\", {param: \"param2\"})\n````\n\n**[Back to top](#table-of-contents)**\n\n## Copying elements\nBefore modifying an object, we sometimes want to copy it and then modify the copied object. We can use `Restangular.copy(fromElement)`.\n\n**[Back to top](#table-of-contents)**\n\n## Using values directly in templates with Observables\n\nIf you want to use values directly in templates use `AsyncPipe`\n\n````js\nthis.accounts = this.restangular.all('accounts').getList();\n````\n\n````html\n\u003ctr *ngFor=\"let account of accounts | async\"\u003e\n  \u003ctd\u003e{{account.fullName}}\u003c/td\u003e\n\u003c/tr\u003e\n````\n\n**[Back to top](#table-of-contents)**\n\n## URL Building\nSometimes, we have a lot of nested entities (and their IDs), but we just want the last child. In those cases, doing a request for everything to get the last child is overkill. For those cases, I've added the possibility to create URLs using the same API as creating a new Restangular object. This connections are created without making any requests. Let's see how to do this:\n\n````javascript\n\nvar restangularSpaces = Restangular.one(\"accounts\",123).one(\"buildings\", 456).all(\"spaces\");\n\n// This will do ONE get to /accounts/123/buildings/456/spaces\nrestangularSpaces.getList()\n\n// This will do ONE get to /accounts/123/buildings/456/spaces/789\nRestangular.one(\"accounts\", 123).one(\"buildings\", 456).one(\"spaces\", 789).get()\n\n// POST /accounts/123/buildings/456/spaces\nRestangular.one(\"accounts\", 123).one(\"buildings\", 456).all(\"spaces\").post({name: \"New Space\"});\n\n// DELETE /accounts/123/buildings/456\nRestangular.one(\"accounts\", 123).one(\"buildings\", 456).remove();\n````\n\n**[Back to top](#table-of-contents)**\n\n## Creating new Restangular Methods\n\nLet's assume that your API needs some custom methods to work. If that's the case, always calling customGET or customPOST for that method with all parameters is a pain in the ass. That's why every element has a `addRestangularMethod` method.\n\nThis can be used together with the hook `addElementTransformer` to do some neat stuff. Let's see an example to learn this:\n\n````javascript\n// Function for settting the default restangular configuration\nexport function RestangularConfigFactory (RestangularProvider) {\n  // It will transform all building elements, NOT collections\n  RestangularProvider.addElementTransformer('buildings', false, function(building) {\n    // This will add a method called evaluate that will do a get to path evaluate with NO default\n    // query params and with some default header\n    // signature is (name, operation, path, params, headers, elementToPost)\n\n    building.addRestangularMethod('evaluate', 'get', 'evaluate', undefined, {'myHeader': 'value'});\n\n    return building;\n  });\n\n  RestangularProvider.addElementTransformer('users', true, function(user) {\n    // This will add a method called login that will do a POST to the path login\n    // signature is (name, operation, path, params, headers, elementToPost)\n\n    user.addRestangularMethod('login', 'post', 'login');\n\n    return user;\n  });\n}\n\n// AppModule is the main entry point into Angular2 bootstraping process\n@NgModule({\n  bootstrap: [ AppComponent ],\n  imports: [ // import Angular's modules\n    RestangularModule.forRoot(RestangularConfigFactory),\n  ],\n})\n\n// Then, later in your code you can do the following:\n\n// GET to /buildings/123/evaluate?myParam=param with headers myHeader: value\n\n// Signature for this \"custom created\" methods is (params, headers, elem) if it's a safe operation (GET, OPTIONS, etc.)\n// If it's an unsafe operation (POST, PUT, etc.), signature is (elem, params, headers).\n\n// If something is set to any of this variables, the default set in the method creation will be overridden\n// If nothing is set, then the defaults are sent\nRestangular.one('buildings', 123).evaluate({myParam: 'param'});\n\n// GET to /buildings/123/evaluate?myParam=param with headers myHeader: specialHeaderCase\n\nRestangular.one('buildings', 123).evaluate({myParam: 'param'}, {'myHeader': 'specialHeaderCase'});\n\n// Here the body of the POST is going to be {key: value} as POST is an unsafe operation\nRestangular.all('users').login({key: value});\n\n````\n\n**[Back to top](#table-of-contents)**\n\n## Adding Custom Methods to Collections\n\nCreate custom methods for your collection using Restangular.extendCollection(). This is an alias for:\n\n```js\n  RestangularProvider.addElementTransformer(route, true, fn);\n```\n\n### Example:\n```js\n  // create methods for your collection\n  Restangular.extendCollection('accounts', function(collection) {\n    collection.totalAmount = function() {\n      // implementation here\n    };\n\n    return collection;\n  });\n\n  var accounts$ = Restangular.all('accounts').getList();\n\n  accounts$.subscribe( accounts =\u003e {\n    accounts.totalAmount(); // invoke your custom collection method\n  });\n```\n\n**[Back to top](#table-of-contents)**\n\n## Adding Custom Methods to Models\n\nCreate custom methods for your models using Restangular.extendModel(). This is an alias for:\n\n```js\n  RestangularProvider.addElementTransformer(route, false, fn);\n```\n\n**[Back to top](#table-of-contents)**\n\n### Example:\n```js\n  Restangular.extendModel('accounts', function(model) {\n    model.prettifyAmount = function() {};\n    return model;\n  });\n\n  var account$ = Restangular.one('accounts', 1).get();\n\n  account$.subscribe(function(account) {\n    account.prettifyAmount(); // invoke your custom model method\n  });\n```\n\n**[Back to top](#table-of-contents)**\n\n# FAQ\n\n#### **How can I handle errors?**\n\nErrors can be checked on the second argument of the subscribe.\n\n````javascript\nRestangular.all(\"accounts\").getList().subscribe( response =\u003e {\n  console.log(\"All ok\");\n}, errorResponse =\u003e {\n  console.log(\"Error with status code\", errorResponse.status);\n});\n````\n\n#### **I need to send Authorization token in EVERY Restangular request, how can I do this?**\n\nYou can use `setDefaultHeaders` or `addFullRequestInterceptor`\n\n````javascript\nimport { NgModule } from '@angular/core';\nimport { AppComponent } from './app.component';\nimport { RestangularModule } from 'ng2-restangular';\nimport { authService } from '../your-services';\n\n// Function for settting the default restangular configuration\nexport function RestangularConfigFactory (RestangularProvider, authService) {\n\n  // set static header\n  RestangularProvider.setDefaultHeaders({'Authorization': 'Bearer UDXPx-Xko0w4BRKajozCVy20X11MRZs1'});\n  \n  // by each request to the server receive a token and update headers with it\n  RestangularProvider.addFullRequestInterceptor((element, operation, path, url, headers, params) =\u003e {\n    let bearerToken = authService.getBearerToken();\n      \n    return {\n      headers: Object.assign({}, headers, {Authorization: `Bearer ${bearerToken}`})\n    };\n  });\n}\n\n// AppModule is the main entry point into Angular2 bootstraping process\n@NgModule({\n  bootstrap: [ AppComponent ],\n  declarations: [\n    AppComponent,\n  ],\n  imports: [\n    // Importing RestangularModule and making default configs for restanglar\n    RestangularModule.forRoot([authService], RestangularConfigFactory),\n  ]\n})\nexport class AppModule {\n}\n````\n**[Back to top](#table-of-contents)**\n\n\n#### **I need to send one header in EVERY Restangular request, how can I do this?**\n\nYou can use `defaultHeaders` property for this. `defaultsHeaders` can be scoped with `withConfig` so it's really cool.\n\n#### **How can I send a delete WITHOUT a body?**\n\nYou must add a requestInterceptor for this.\n\n````js\nRestangularProvider.setRequestInterceptor(function(elem, operation) {\n  if (operation === \"remove\") {\n     return null;\n  }\n  return elem;\n})\n````\n\n#### **I use Mongo and the ID of the elements is `_id` not `id` as the default. Therefore requests are sent to undefined routes**\n\nWhat you need to do is to configure the `RestangularFields` and set the `id` field to `_id`. Let's see how:\n\n````javascript\nRestangularProvider.setRestangularFields({\n  id: \"_id\"\n});\n````\n\n#### **What if each of my models has a different ID name like CustomerID for Customer**\n\nIn some cases, people have different ID name for each entity. For example, they have CustomerID for customer and EquipmentID for Equipment. If that's the case, you can override Restangular's getIdFromElem. For that, you need to do:\n\n````js\nRestangularProvider.configuration.getIdFromElem = function(elem) {\n  // if route is customers ==\u003e returns customerID\n  return elem[_.initial(elem.route).join('') + \"ID\"];\n}\n````\nWith that, you'd get what you need :)\n\n#### **How can I send files in my request using Restangular?**\n\nThis can be done using the customPOST / customPUT method. Look at the following example:\n````js\nRestangular.all('users')\n.customPOST(formData, undefined, undefined, { 'Content-Type': undefined });\n````\nThis basically tells the request to use the *Content-Type: multipart/form-data* as the header. Also *formData* is the body of the request, be sure to add all the params here, including the File you want to send of course.\n\n#### **How do I handle CRUD operations in a List returned by Restangular?**\n\n````javascript\nRestangular.all('users').getList().subscribe( users =\u003e {\n  this.users = users;\n  var userWithId = _.find(users, function(user) {\n    return user.id === 123;\n  });\n\n  userWithId.name = \"Gonto\";\n  userWithId.put();\n\n  // Alternatively delete the element from the list when finished\n  userWithId.remove().subscribe( () =\u003e {\n    // Updating the list and removing the user after the response is OK.\n    this.users = _.without(this.users, userWithId);\n  });\n\n});\n````\n\n#### Removing an element from a collection, keeping the collection restangularized\n\nWhile the example above removes the deleted user from the collection, it also overwrites the collection object with a plain array (because of `_.without`) which no longer knows about its Restangular attributes.\n\nIf want to keep the restangularized collection, remove the element by modifying the collection in place:\n\n```javascript\nuserWithId.remove().subscribe( () =\u003e {\n  let index = $scope.users.indexOf(userWithId);\n  if (index \u003e -1) this.users.splice(index, 1);\n});\n```\n\n#### How can I access the `unrestangularized` element as well as the `restangularized` one?\n\nIn order to get this done, you need to use the `responseExtractor`. You need to set a property there that will point to the original response received. Also, you need to actually copy this response as that response is the one that's going to be `restangularized` later\n\n````javascript\nRestangularProvider.setResponseExtractor( (response) =\u003e {\n  var newResponse = response;\n  if (_.isArray(response)) {\n    _.forEach(newResponse, function(value, key) {\n      newResponse[key].originalElement = _.clone(value);\n    });\n  } else {\n    newResponse.originalElement = _.clone(response);\n  }\n\n  return newResponse;\n});\n````\nAlternatively, if you just want the stripped out response on any given call, you can use the .plain() method, doing something like this:\n\n````javascript\n\nthis.showData = function () {\n  baseUrl.post(someData).subscribe( (response) =\u003e {\n    console.log(response.plain());\n  });\n};\n````\n\n**[Back to top](#table-of-contents)**\n\n#### How can add withCredentials params to requests?\n````javascript\n// Function for settting the default restangular configuration\nexport function RestangularConfigFactory (RestangularProvider) {\n  // Adding withCredential parametr to all Restangular requests\n  RestangularProvider.setDefaultHttpFields({ withCredentials: true });\n}\n\n@NgModule({\n  bootstrap: [ AppComponent ],\n  declarations: [\n    AppComponent,\n  ],\n  imports: [\n    // Global configuration\n    RestangularModule.forRoot(RestangularConfigFactory),\n  ]\n})\nexport class AppModule {}\n ````\n\n**[Back to top](#table-of-contents)**\n\n# Server Frameworks\n\nUsers reported that this server frameworks play real nice with Ng2-Restangular, as they let you create a Nested RESTful Resources API easily:\n\n* Ruby on Rails\n* CakePHP, Laravel and FatFREE, Symfony2 with RestBundle, Silex for PHP\n* Play1 \u0026 2 for Java \u0026 scala\n* Dropwizard for Java\n* Restify and Express for NodeJS\n* Tastypie and Django Rest Framework for Django\n* Slim Framework\n* Symfony2 with FOSRestBundle (PHP)\n* Microsoft ASP.NET Web API 2\n* Grails Framework\n\n**[Back to top](#table-of-contents)**\n\n# License\n\nThe MIT License\n\n**[Back to top](#table-of-contents)**\n","funding_links":[],"categories":["Uncategorized"],"sub_categories":["Uncategorized"],"project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2F2muchcoffeecom%2Fng2-restangular","html_url":"https://awesome.ecosyste.ms/projects/github.com%2F2muchcoffeecom%2Fng2-restangular","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2F2muchcoffeecom%2Fng2-restangular/lists"}