Thisprojectisthefollow-upoftheRestangular.Ngx-restangularisanAngular2+servicethatsimplifiescommonGET,POST,DELETE,andUPDATErequestswithaminimumofclientcode.It'saperfectfitforanyWebAppthatconsumesdatafromaRESTfulAPI.
DemoYoucancheckpostaboutusingngx-restangularinRESTfulAPIAngularSolution
CurrentstageNgx-restangularalmostallfunctionalitywastransferredfromtheRestangular.Weareopentoanycooperationintermsofitsfurtherdevelopment.
Renamingprojectfromng2-restangulartongx-restangularThisprojectwasrenamedfromng2-restangulartongx-restangularduetoimplementationofSemanticVersioningbyAngularCoreTeam.NPMnamehasalsochanged,youcaninstallactualversionoftheprojectwithnpminstallngx-restangular.
TableofcontentsHowdoIaddthistomyprojectinangular5+?
HowdoIaddthistomyprojectinangular4?
HowdoIaddthistomyprojectinangular2?
Dependencies
StarterGuide
QuickconfigurationforLazyReadersUsingRestangularCreatingMainRestangularobjectLetsCodewithObservables!HereisExampleofcodewithusingpromises!ConfiguringRestangularPropertieswithConfigsetBaseUrlsetExtraFieldssetParentlessaddElementTransformersetTransformOnlyServerElementssetOnElemRestangularizedaddResponseInterceptoraddFullRequestInterceptoraddErrorInterceptorsetRestangularFieldssetMethodOverriderssetDefaultRequestParamssetFullResponsesetDefaultHeaderssetRequestSuffixsetUseCannonicalIdsetPlainByDefaultsetEncodeIdsAccessingconfigurationHowtoconfigurethemgloballyConfiguringintheAppModuleConfiguringintheAppModulewithDependencyInjectionappliedHowtocreateaRestangularservicewithadifferentconfigurationfromtheglobaloneDecoupledRestangularServiceMethodsdescriptionRestangularmethodsElementmethodsCollectionmethodsCustommethodsCopyingelementsUsingvaluesdirectlyintemplateswithObservablesURLBuildingCreatingnewRestangularMethodsAddingCustomMethodstoCollectionsExample:AddingCustomMethodstoModelsExample:FAQ
HowcanIhandleerrors?IneedtosendAuthorizationtokeninEVERYRestangularrequest,howcanIdothis?IneedtosendoneheaderinEVERYRestangularrequest,howcanIdothis?HowcanIsendadeleteWITHOUTabody?IuseMongoandtheIDoftheelementsis_idnotidasthedefault.ThereforerequestsaresenttoundefinedroutesWhatifeachofmymodelshasadifferentIDnamelikeCustomerIDforCustomerHowcanIsendfilesinmyrequestusingRestangular?HowdoIhandleCRUDoperationsinaListreturnedbyRestangular?Removinganelementfromacollection,keepingthecollectionrestangularizedHowcanIaccesstheunrestangularizedelementaswellastherestangularizedone?HowcanaddwithCredentialsparamstorequests?ServerFrameworks
Contributing
License
Backtotop
HowdoIaddthistomyprojectinangular5+?Youcandownloadthisbynpmandrunningnpminstallngx-restangular.Thiswillinstalllatestversionofngx-restangular(v.2.0.0).
Backtotop
HowdoIaddthistomyprojectinangular4?Youcandownloadthisbynpmandrunningnpminstall--savengx-restangular@1.0.13
Versionsfrom1.0.14to1.1.4aredeprecated.Npmwarnsyouaftertheirinstallation.Thoseversionswouldberemoved.
Backtotop
HowdoIaddthistomyprojectinangular2?Youcandownloadthisbynpmandrunningnpminstallng2-restangular
Backtotop
DependenciesRestangulardependsonAngular2+andLodash.
Backtotop
StarterGuideQuickConfiguration(ForLazyReaders)ThisisallyouneedtostartusingallthebasicRestangularfeatures.
import{NgModule}from'@angular/core';import{AppComponent}from'./app.component';import{RestangularModule,Restangular}from'ngx-restangular';//FunctionforsettingthedefaultrestangularconfigurationexportfunctionRestangularConfigFactory(RestangularProvider){RestangularProvider.setBaseUrl('https://api.restngx.local/v1');RestangularProvider.setDefaultHeaders({'Authorization':'BearerUDXPx-Xko0w4BRKajozCVy20X11MRZs1'});}//AppModuleisthemainentrypointintoAngular2bootstrapingprocess@NgModule({bootstrap:[AppComponent],declarations:[AppComponent,],imports:[//ImportingRestangularModuleandmakingdefaultconfigsforrestanglarRestangularModule.forRoot(RestangularConfigFactory),]})exportclassAppModule{}//laterincode...@Component({...})exportclassOtherComponent{constructor(privaterestangular:Restangular){}ngOnInit(){//GEThttps://api.test.local/v1/users/2/accountsthis.restangular.one('users',2).all('accounts').getList();}Backtotop
UsingRestangularCreatingMainRestangularobjectThereare3waysofcreatingamainRestangularobject.Thefirstoneandmostcommononeisbystatingthemainrouteofallrequests.Thesecondoneisbystatingthemainrouteandobjectofallrequests.
//OnlystatingmainrouteRestangular.all('accounts')//StatingmainobjectRestangular.one('accounts',1234)//GetsalistofallofthoseaccountsRestangular.several('accounts',1234,123,12345);Backtotop
LetsCodewithObservables!NowthatwehaveourmainObjectlet'sstartplayingwithit.
//AppModuleisthemainentrypointintoAngular2bootstrapingprocess@NgModule({bootstrap:[AppComponent],declarations:[AppComponent,],imports:[//ImportingRestangularModuleRestangularModule,]})exportclassAppModule{}@Component({...})exportclassOtherComponent{allAccounts;accounts;account;constructor(privaterestangular:Restangular){}ngOnInit(){//Firstwayofcreatingathis.restangularobject.JustsayingthebaseURLletbaseAccounts=this.restangular.all('accounts');//Thiswillquery/accountsandreturnaobservable.baseAccounts.getList().subscribe(accounts=>{this.allAccounts=accounts;});letnewAccount={name:"Gonto'saccount"};//POST/accountsbaseAccounts.post(newAccount);//GETtohttps://www.google.com/YousettheURLinthiscasethis.restangular.allUrl('googlers','https://www.google.com/').getList();//GETtohttps://www.google.com/1YousettheURLinthiscasethis.restangular.oneUrl('googlers','https://www.google.com/1').get();//YoucandoRequestLess"connections"ifyouneedaswell//JustONEGETto/accounts/123/buildings/456this.restangular.one('accounts',123).one('buildings',456).get();//JustONEGETto/accounts/123/buildingsthis.restangular.one('accounts',123).getList('buildings');//HereweuseObservables//GET/accountsletbaseAccounts$=baseAccounts.getList().subscribe(accounts=>{//Herewecancontinuefetchingthetree:).letfirstAccount=accounts[0];//Thiswillquery/accounts/123/buildingsconsidering123istheidofthefirstAccountletbuildings=firstAccount.getList("buildings");//GET/accounts/123/places?query=paramwithrequestheader:x-user:mgontoletloggedInPlaces=firstAccount.getList("places",{query:'param'},{'x-user':'mgonto'});//ThisisaregularJSobject,wecanchangeanythingwewant:)firstAccount.name="Gonto";//Ifwewantedtokeeptheoriginalasitis,wecancopyittoanewelementleteditFirstAccount=this.restangular.copy(firstAccount);editFirstAccount.name="NewName";//PUT/accounts/123.ThenameofthisaccountwillbechangedfromnowonfirstAccount.put();editFirstAccount.put();//PUT/accounts/123.SavewilldoPOSTorPUTaccordinglyfirstAccount.save();//DELETE/accounts/123Wedon'thavefirstaccountanymore:(firstAccount.remove();},()=>{alert("Oopserrorfromserver:(");});//GetfirstaccountletfirstAccount$=baseAccounts$.map(accounts=>accounts[0]);//POST/accounts/123/buildingswithMyBuildinginformationfirstAccount$.switchMap(firstAccount=>{varmyBuilding={name:"Gonto'sBuilding",place:"Argentina"};returnfirstAccount.post("Buildings",myBuilding)}).subscribe(()=>{console.log("ObjectsavedOK");},()=>{console.log("Therewasanerrorsaving");});//GET/accounts/123/users?query=paramsfirstAccount$.switchMap(firstAccount=>{varmyBuilding={name:"Gonto'sBuilding",place:"Argentina"};returnfirstAccount.getList("users",{query:'params'});}).subscribe((users)=>{//Insteadofpostingnestedelement,acollectioncanposttoitself//POST/accounts/123/usersusers.post({userName:'unknown'});//Custommethodsareavailablenow:).//GET/accounts/123/users/messages?param=myParamusers.customGET("messages",{param:"myParam"});varfirstUser=users[0];//GET/accounts/123/users/456.Justincasewewanttoupdateoneuser:)letuserFromServer=firstUser.get();//ALLhttpmethodsareavailable:)//HEAD/accounts/123/users/456firstUser.head()},()=>{console.log("Therewasanerrorsaving");});//Secondwayofcreatingthis.restangularobject.URLandID:)varaccount=this.restangular.one("accounts",123);//GET/accounts/123?single=truethis.account=account.get({single:true});//POST/accounts/123/messages?param=myParamwiththebodyofname:"MyMessage"account.customPOST({name:"MyMessage"},"messages",{param:"myParam"},{})}}Backtotop
HereisExampleofcodewithusingpromises!@Component({...})exportclassOtherComponent{allAccounts;accounts;account;constructor(privaterestangular:Restangular){}ngOnInit(){//Firstwayofcreatingathis.restangularobject.JustsayingthebaseURLletbaseAccounts=this.restangular.all('accounts');//Thiswillquery/accountsandreturnapromise.baseAccounts.getList().toPromise().then(function(accounts){this.allAccounts=accounts;});varnewAccount={name:"Gonto'saccount"};//POST/accountsbaseAccounts.post(newAccount);//GETtohttps://www.google.com/YousettheURLinthiscasethis.restangular.allUrl('googlers','https://www.google.com/').getList();//GETtohttps://www.google.com/1YousettheURLinthiscasethis.restangular.oneUrl('googlers','https://www.google.com/1').get();//YoucandoRequestLess"connections"ifyouneedaswell//JustONEGETto/accounts/123/buildings/456this.restangular.one('accounts',123).one('buildings',456).get();//JustONEGETto/accounts/123/buildingsthis.restangular.one('accounts',123).getList('buildings');//HereweusePromisesthen//GET/accountsbaseAccounts.getList().toPromise().then(function(accounts){//Herewecancontinuefetchingthetree:).varfirstAccount=accounts[0];//Thiswillquery/accounts/123/buildingsconsidering123istheidofthefirstAccountthis.buildings=firstAccount.getList("buildings");//GET/accounts/123/places?query=paramwithrequestheader:x-user:mgontothis.loggedInPlaces=firstAccount.getList("places",{query:'param'},{'x-user':'mgonto'});//ThisisaregularJSobject,wecanchangeanythingwewant:)firstAccount.name="Gonto";//Ifwewantedtokeeptheoriginalasitis,wecancopyittoanewelementvareditFirstAccount=this.restangular.copy(firstAccount);editFirstAccount.name="NewName";//PUT/accounts/123.ThenameofthisaccountwillbechangedfromnowonfirstAccount.put();editFirstAccount.put();//PUT/accounts/123.SavewilldoPOSTorPUTaccordinglyfirstAccount.save();//DELETE/accounts/123Wedon'thavefirstaccountanymore:(firstAccount.remove();varmyBuilding={name:"Gonto'sBuilding",place:"Argentina"};//POST/accounts/123/buildingswithMyBuildinginformationfirstAccount.post("Buildings",myBuilding).toPromise().then(function(){console.
评论