Giter Site home page Giter Site logo

2muchcoffeecom / ngx-restangular Goto Github PK

View Code? Open in Web Editor NEW
782.0 36.0 110.0 3.16 MB

Restangular for Angular 2 and higher versions

Home Page: https://2muchcoffee.com/ngxrestangular-app-development

License: MIT License

TypeScript 96.02% JavaScript 3.98%
angular angular2 rest-api reactive restful restful-api rest-client rxjs observable fetch

ngx-restangular's People

Contributors

bal3no avatar birot avatar corinnekrych avatar kamaruzzaman avatar logvinoleg89 avatar matteobaldelli avatar niklasteich avatar nubinub avatar otaran avatar patkec avatar roadhero avatar rshchpkn avatar snisarch avatar tairezzzz avatar tamascsaba avatar timaxapa avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

ngx-restangular's Issues

Module not found

After running 'npm install ng2-restangular'

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { AppComponent }   from './app.component';
import { RestangularModule } from 'ng2-restangular';
@NgModule({
  imports:      [ BrowserModule,     
                    RestangularModule.forRoot((RestangularProvider) => {
                        RestangularProvider.setBaseUrl('http://localhost:3011/api');
                        RestangularProvider.setDefaultHeaders({'Authorization': 'Bearer UDXPx-Xko0w4BRKajozCVy20X11MRZs1'});
                      }
                    )  ],
  declarations: [ AppComponent ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

and adding it in the app.module.ts, I got:

localhost/:23 Error: (SystemJS) XHR error (404 Not Found) loading http://localhost:3000/ng2-restangular(…)

I'm new to Angular2 and can't find why. Any clue?

issue on set session in header

Hi,
I am using restangular in my project, i jjust set that global restangular factory in app.module it will load first time when my home page loads. but after logged in in it will not refresh the restangular after set the session key, its only display session token as empty and display after reload the page.
please help me to solve that issue

Is ErrorInterceptor Working

Hello, I was trying to use this library but I had a problem using addErrorInterceptor. Error Interceptor is correctly working? I see the tests and I notices that test of ErrorInterceptor was comented...please let me know if I should use it or will be available soon?

no provider for http error

I'm using the lastest version of angular2 with ng2-restangular.

This is related with this question in StackOverflow.

Error: No provider for Http!

This ocourrs when I try to inject restangular in any component/page.

import {Restangular} from "ng2-restangular";

@Component({
    selector: 'my-app',
    template: require('./app.component.html')
})

export class AppComponent implements OnInit {
    constructor(private restangular: Restangular) {
    }

    ngOnInit() {
        // GET http://api.test.local/v1/users/2/accounts
        this.restangular.one('users', 2).all("accounts").getList();
    }
}

Add Contribution Guidelines

Hi

I wish to start contributing to the package in any ways I can. I also created a fork of the repository and tried to use that in my project (But that didn't work). It would be great if we can publish some guideline on how to contribute (with build steps) so that people like me can go ahead and help you in the awesome stuff that you are doing. :-)

Specifically, the first thing that I wish to start with is typings.

FAQ - Processing Errors with Observables

Currently the FAQ has the following code to handle errors from REST calls.

Restangular.all("accounts").getList().subscribe( response => {
  console.log("All ok");
}, errorResponse {
  console.log("Error with status code", errorResponse.status);
});

The code is missing the => for the errorResponse. It should read:

  console.log("All ok");
}, errorResponse => {
  console.log("Error with status code", errorResponse.status);
});

Thanks for the project, by the way! Really great!

Update name of the project

Angular4 will be released at 2017 march. I think it will be good rename the project to ngx-restangular or ngx-rest or something else.

angular4-tentativeschedule

cache: true not working

When setting RestangularProvider.setDefaultHttpFields({cache: true}); it still does the requests to the server when navigating the routes

Issue with angular beta-4

Hey!

I took my repo and did npm install on a different computer and am now getting an error (no code changes, nothing). A package had to have updated that hasnt before. Any help with this would be much appreciated.

The error is:

ERROR in Error encountered resolving symbol values statically. Calling function 'OpaqueToken', function calls are not supported. Consider replacing the function or lambda with a reference to an exported function, resolving symbol CONFIG_OBJ in /Users/Au/Projects/AU/M/app.io/node_modules/ng2-restangular/dist/esm/src/ng2-restangular.module.d.ts, resolving symbol RestangularModule.forRoot in /Users/Au/Projects/AU/mo/app.io/node_modules/ng2-restangular/dist/esm/src/ng2-restangular.module.d.ts, resolving symbol AppModule in /Users/Au/Projects/AU/mo/app.io/src/app/app.module.ts, resolving symbol AppModule in /Users/Au/Projects/AU/mo/app.io/src/app/app.module.ts

My app.module looks like this:

export function configFunc (RestangularProvider, http) {
  RestangularProvider.setBaseUrl('...');
}

@NgModule({
    declarations: [
        AppComponent,
    ],
    imports: [
        BrowserModule,
        TranslateModule.forRoot(),
        SharedModule,

        RoutingModule,
        RestangularModule.forRoot([Http], configFunc)

    ],
    providers: [],
    bootstrap: [AppComponent]
})
export class AppModule { }   

I am using:
Angular 4.0.0-beta.4 and angular-cli 1.0.0-beta.26

Thanks!

No provider for Http

core.umd.js?e2a5:2840Error: No provider for Http!
    at NoProviderError.Error (native)
    at NoProviderError.BaseError [as constructor] (eval at <anonymous> (http://localhost:3000/vendor.js:100:2), <anonymous>:1104:38)
    at NoProviderError.AbstractProviderError [as constructor] (eval at <anonymous> (http://localhost:3000/vendor.js:100:2), <anonymous>:1235:20)
    at new NoProviderError (eval at <anonymous> (http://localhost:3000/vendor.js:100:2), <anonymous>:1266:20)
    at ReflectiveInjector_._throwOrNull (eval at <anonymous> (http://localhost:3000/vendor.js:100:2), <anonymous>:2736:23)
    at ReflectiveInjector_._getByKeyDefault (eval at <anonymous> (http://localhost:3000/vendor.js:100:2), <anonymous>:2764:29)
    at ReflectiveInjector_._getByKey (eval at <anonymous> (http://localhost:3000/vendor.js:100:2), <anonymous>:2727:29)
    at ReflectiveInjector_.get (eval at <anonymous> (http://localhost:3000/vendor.js:100:2), <anonymous>:2536:25)
    at NgModuleInjector.get (/AppModule/module.ngfactory.js:160:113)
    at NgModuleInjector.get (/AppModule/module.ngfactory.js:165:135)
    at NgModuleInjector.AppModuleInjector.getInternal (/AppModule/module.ngfactory.js:306:51)
    at NgModuleInjector.get (eval at <anonymous> (http://localhost:3000/vendor.js:100:2), <anonymous>:6717:31)
    at DebugAppView.AppView.injectorGet (eval at <anonymous> (http://localhost:3000/vendor.js:100:2), <anonymous>:9150:49)
    at DebugAppView.injectorGet (eval at <anonymous> (http://localhost:3000/vendor.js:100:2), <anonymous>:9389:53)
    at DebugAppView.View_AppComponent_Host0.createInternal (/AppModule/AppComponent/host.ngfactory.js:15:63)
    at DebugAppView.AppView.createHostView (eval at <anonymous> (http://localhost:3000/vendor.js:100:2), <anonymous>:9122:25)
    at DebugAppView.createHostView (eval at <anonymous> (http://localhost:3000/vendor.js:100:2), <anonymous>:9379:56)
    at ComponentFactory.create (eval at <anonymous> (http://localhost:3000/vendor.js:100:2), <anonymous>:5478:29)
    at ApplicationRef_.bootstrap (eval at <anonymous> (http://localhost:3000/vendor.js:100:2), <anonymous>:6547:44)
    at eval (eval at <anonymous> (http://localhost:3000/vendor.js:100:2), <anonymous>:6456:93)
    at Array.forEach (native)
    at PlatformRef_._moduleDoBootstrap (eval at <anonymous> (http://localhost:3000/vendor.js:100:2), <anonymous>:6456:46)
    at eval (eval at <anonymous> (http://localhost:3000/vendor.js:100:2), <anonymous>:6424:31)
    at ZoneDelegate.invoke (eval at <anonymous> (http://localhost:3000/polyfills.js:2179:2), <anonymous>:232:26)
    at Object.onInvoke (eval at <anonymous> (http://localhost:3000/vendor.js:100:2), <anonymous>:5972:41)
    at ZoneDelegate.invoke (eval at <anonymous> (http://localhost:3000/polyfills.js:2179:2), <anonymous>:231:32)
    at Zone.run (eval at <anonymous> (http://localhost:3000/polyfills.js:2179:2), <anonymous>:114:43)
    at eval (eval at <anonymous> (http://localhost:3000/polyfills.js:2179:2), <anonymous>:502:57)
    at ZoneDelegate.invokeTask (eval at <anonymous> (http://localhost:3000/polyfills.js:2179:2), <anonymous>:265:35)
    at Object.onInvokeTask (eval at <anonymous> (http://localhost:3000/vendor.js:100:2), <anonymous>:5963:41)
    at ZoneDelegate.invokeTask (eval at <anonymous> (http://localhost:3000/polyfills.js:2179:2), <anonymous>:264:40)
    at Zone.runTask (eval at <anonymous> (http://localhost:3000/polyfills.js:2179:2), <anonymous>:154:47)
    at drainMicroTaskQueue (eval at <anonymous> (http://localhost:3000/polyfills.js:2179:2), <anonymous>:401:35)

I get this stack trace when i attempt to follow the quick start guide,

the problem comes about when i add the code into my app.component.ts

import {Component, OnInit} from '@angular/core';

import 'bootstrap/dist/css/bootstrap.css';
import '../css/main.css';
import {Restangular} from "ng2-restangular";


@Component({
    selector: 'my-app',
    template: require('./app.component.html')
})

export class AppComponent implements OnInit {
    constructor(public restangular: Restangular) {
    }

    ngOnInit() {
        // GET http://api.test.local/v1/users/2/accounts
        this.restangular.one('users', 2).all("accounts").getList();
    }
}

please excuse me if this turns out it is an issue with my setup of this project but there seems to be very little in the way of answers when i google fu this.

If i remove the constructor and put a console.debug into ngOnInit with a string in conjunction with importing RestAngular into the app.modules.ts like so:


import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
import {FormsModule} from '@angular/forms';
import {AppComponent} from './app.component';
import {HttpModule, Headers, Response, ResponseOptions} from "@angular/http";
import {RestangularModule} from 'ng2-restangular';
import {routing, appRoutingProviders} from './app.routing';
import {HomeComponent} from './home/home.component';
import {AboutComponent} from './about/about.component';


@NgModule({
    declarations: [
        AppComponent,
        HomeComponent,
        AboutComponent
    ],
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        routing,
        // Importing RestangularModule and making default configs for restanglar
        RestangularModule.forRoot((RestangularProvider: any) => {
                RestangularProvider.setBaseUrl('http://api.test.local/v1');
                RestangularProvider.setDefaultHeaders({'Authorization': 'Bearer UDXPx-Xko0w4BRKajozCVy20X11MRZs1'});
            }
        ),
    ],
    providers: [],
    bootstrap: [AppComponent]
})

export class AppModule {
}

export class AppModule {
}

i get no errors and all is well but then I have to wonder what it is I am missing to be able to get this working in one of my modules

Observable failure

When I call the .getList method, when it finishes executing it doesn't call the method Observable.finally.

 Restangular
  .one("accounts",123)
  .one("buildings", 456)
  .all("spaces")
  .getList()
  .finally(() => console.log("Done!"))
  .subscribe((users) => console.log(users));

Property 'withConfig' does not exist on type 'RestangularModule'.

trying out code from the doc:

//Restangular service that uses Bing
export const RESTANGULAR_BING = new OpaqueToken('RestangularBing');
export function RestangularBingFactory(restangular: RestangularModule) {
  return restangular.withConfig((RestangularConfigurer) => {
     RestangularConfigurer.setBaseUrl('http://www.bing.com');
   });
}

But it´s not working.. ?

No provider for Http

It seems that this error have come back, I am using 0.1.21

Error: Uncaught (in promise): Error: Error in ./AppComponent class AppComponent - inline template:2:4 caused by: No provider for Http!
Error: No provider for Http!
    at NoProviderError.BaseError [as constructor] (core.umd.js:1104)
    at NoProviderError.AbstractProviderError [as constructor] (core.umd.js:1235)
    at new NoProviderError (core.umd.js:1266)
    at ReflectiveInjector_._throwOrNull (core.umd.js:2739)
    at ReflectiveInjector_._getByKeyDefault (core.umd.js:2767)
    at ReflectiveInjector_._getByKey (core.umd.js:2730)
    at ReflectiveInjector_.get (core.umd.js:2539)
    at AppModuleInjector.get (module.ngfactory.js:220)
    at AppModuleInjector.get (module.ngfactory.js:225)
    at AppModuleInjector.get (module.ngfactory.js:329)
    at NoProviderError.BaseError [as constructor] (core.umd.js:1104)
    at NoProviderError.AbstractProviderError [as constructor] (core.umd.js:1235)
    at new NoProviderError (core.umd.js:1266)

Angular 4 - OpaqueToken issue

I tried to update my app to angular 4 and OpaqueToken issue occurred.
ERROR in Error encountered resolving symbol values statically. Calling function 'OpaqueToken', function calls are not supported. Consider replacing the function or lambda with a reference to an exported function, resolving symbol CONFIG_OBJ in /home/baidario/Projects/insta-clone/frontend/node_modules/ng2-restangular/dist/esm/src/ng2-restangular.module.d.ts, resolving symbol RestangularModule.forRoot in /home/baidario/Projects/insta-clone/frontend/node_modules/ng2-restangular/dist/esm/src/ng2-restangular.module.d.ts, resolving symbol AppModule in /home/baidario/Projects/insta-clone/frontend/src/app/app.module.ts, resolving symbol AppModule in /home/baidario/Projects/insta-clone/frontend/src/app/app.module.ts

Here is my app.module.ts file:

export function RestangularConfigFactory(RestangularProvider, http, router) {
  RestangularProvider.setBaseUrl('http://127.0.0.1:3000');
  RestangularProvider.setDefaultHeaders({ 'Content-Type': 'application/json' });

  RestangularProvider.addFullRequestInterceptor(
    (element, operation, path, url, headers, params) => {
      const token = localStorage.getItem('token');
      return { headers: Object.assign({ }, headers, { 'Authorization': `JWT ${token}` }) }
    }
  );
};

@NgModule({
  declarations: [ ... ],
  imports: [
    ...
    RestangularModule.forRoot([Http, Router], RestangularConfigFactory)
  ],
  providers: [ ... ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Will you migrate your module to angular 4?

how to use router in interceptors

Hi. I'm new at angular2 maybe that's why I do not know how to call a router to make a redirect to another route from the interceptor. For example when the token has expired redirect the user to the login. It did it previously with angular 1 and restangular. Thank you very much

Subscribe on put and save doesn't work

angular: 2.4.1
ng2-restangular: ^0.1.28

The following code calls the put successfully, but neither code blocks (success or fail) are called.

    this._accountService.account.put().subscribe( <- this works, the record is saved to the db
      (res) => {
        this._notifier.success("Saved","Account was successfully saved.");  <- not called on success
        this._router.navigate(['/references/accounts']); <- not called on success
      }, 
      (err) => {
        this._notifer.error("Server Error", 'Account was not saved: ' + err); <- not called on error
      }

How do you do error checking on put or save calls? I haven't tested this with post.

Thank you for this incredible tool.

Testing with Angular-Seed

Hi, sorry for brother, I'm new in angular 2, but anyone test ng2-restangular with angular-seed starter? its a good start
https://github.com/mgechev/angular-seed

I have the following error at module import

02:17:27.556 "(SystemJS) XHR error (404 Not Found) loading http://localhost:5555/node_modules/rxjs.js
patchProperty/desc.set/wrapFn@http://localhost:5555/node_modules/zone.js/dist/zone.js?1489194053152:1190:26 []
Zone.prototype.runTask@http://localhost:5555/node_modules/zone.js/dist/zone.js?1489194053152:166:28 [ => ]
ZoneTask/this.invoke@http://localhost:5555/node_modules/zone.js/dist/zone.js?1489194053152:416:28 []

Error loading http://localhost:5555/node_modules/rxjs.js as "rxjs" from http://localhost:5555/node_modules/ng2-restangular/dist/umd/ng2-restangular.js" "Not expecting this error? Report it at https://github.com/mgechev/angular-seed/issues" 1 localhost:5555:65:7
<anónimo> http://localhost:5555/:65:7
ZoneDelegate.prototype.invoke http://localhost:5555/node_modules/zone.js/dist/zone.js:330:17
Zone.prototype.run http://localhost:5555/node_modules/zone.js/dist/zone.js:126:24
scheduleResolveOrReject/< http://localhost:5555/node_modules/zone.js/dist/zone.js:679:52
ZoneDelegate.prototype.invokeTask http://localhost:5555/node_modules/zone.js/dist/zone.js:363:17
Zone.prototype.runTask http://localhost:5555/node_modules/zone.js/dist/zone.js:166:28
drainMicroTaskQueue http://localhost:5555/node_modules/zone.js/dist/zone.js:529:25
ZoneTask/this.invoke http://localhost:5555/node_modules/zone.js/dist/zone.js:420:25

it seems that rxjs is not loaded in his real path... when loads

I don't know, if is related to a issue of the project or how this project imports rxjs or SystemJs configuration, or a mistake myself but
in other project seems to be fixed replacing
import { Observable, BehaviorSubject } from "rxjs";
with
import { Observable, BehaviorSubject } from "rxjs/Rx";
xmaestro/angular2-recaptcha#31 (comment)

I tryid other modules as angular2-toaster, ng2-breadcrumbs and works well with seed starter, but this not.

I'd be great if restangular could works with this angular-seed as is very popular, or any hint for try to make works.

thanks, I thanks for this project restangular with angular 2

Issue with subscription to remove()

I've tried to subscribe to remove() to do some logging after removal of item and refreshing the grid. But I can't subscribe to remove(). It's send DELETE request and remove element from database. I get 200 - OK from server but on client I can't hit subscribe method after that.

Could you help me somehow?

This is what I've tried:
restangular.one('Inventory', id).remove().subscribe( () => { console.log("blah") })

Unexpected value '[object Object]' imported by the module 'AppModule'

Getting only when attempting to import ng2-restangular, using the docs for "Quick Configuration"
The project is based on the https://github.com/AngularClass/angular2-webpack-starter repo.

Uncaught Error: Unexpected value '[object Object]' imported by the module 'AppModule'(…)

Even removing the function from the .fromRoot(..) method, does nothing. Setting a break point in the function shows it's not getting there at all.

This is my app.module.ts

  import { NgModule, ApplicationRef } from '@angular/core';
  import { CommonModule } from '@angular/common';
  import { BrowserModule } from '@angular/platform-browser';
  import { RouterModule } from '@angular/router';
  import { FormsModule } from '@angular/forms';
  import { HttpModule, XSRFStrategy, CookieXSRFStrategy } from '@angular/http';
  
  import { RestangularModule } from 'ng2-restangular';
  
  // ngrx/store components
  import { StoreModule } from '@ngrx/store';
  import { EffectsModule } from '@ngrx/effects';
  import { RouterStoreModule } from '@ngrx/router-store';
  import { StoreDevtoolsModule } from '@ngrx/store-devtools';
  
  import { MaterialModule } from '@angular/material';
  import { ComponentsModule } from './components/index';
  import { AuthenticationEffects } from './effects/authentication';
  import { UserEffects } from './effects/user';
  import { ListEffects } from './effects/lists';
  
  import { UserAuthenticatedGuard } from './guards/user-authenticated';
  import { PartnerLeadsService } from './services/partner-leads-service';
  import { AuthenticationService } from './services/authentication-service';
  import { ListsService } from './services/lists-service';
  
  // App is our top level component
  import { AppComponent } from './containers/app/app';
  import { LoginPageComponent } from './containers/login-page/login-page';
  import { LeadsPageComponent } from './containers/leads-page/leads-page';
  import { DashboardComponent } from './containers/dashboard/dashboard';
  
  import { routes } from './routes';
  import { reducer } from './reducers';
  
  @NgModule({
    imports: [ // import Angular's modules
      CommonModule,
      HttpModule,
      BrowserModule,
      FormsModule,
      MaterialModule.forRoot(),
      RestangularModule.forRoot((RestangularProvider) => {
        RestangularProvider.setBaseUrl('/api/v1/');
        RestangularProvider.setDefaultHeaders({
           'Authorization': 'Bearer UDXPx-Xko0w4BRKajozCVy20X11MRZs1'
        });
      }),
      ComponentsModule,
      RouterModule.forRoot(routes, { useHash: true }),
      StoreModule.provideStore(reducer),
      RouterStoreModule.connectRouter(),   
      StoreDevtoolsModule.instrumentOnlyWithExtension(),
    ],
    declarations: [
      AppComponent
    ],
    providers: [],
    bootstrap: [
      AppComponent
    ]
  })
  export class AppModule { }

Interceptor/Refresh in AoT (ng-cli)

Angular Version : 2.3.1

Problem : I'm trying to do a refresh request when my token expired but doesn't know where to do the request and put the interceptor. As far as i understand, it's part of the configuration so it should be in my app.module. But I can't execute a Restangular request inside the Config function ?

I'm a bit lost with this way of setting the configuration.

export function configFunc (RestangularProvider, http) {
  RestangularProvider.setBaseUrl('http://localhost:8888/v1');

  // I check before if there is a currentUser token available.
  let currentUser = JSON.parse(localStorage.getItem('currentUser'));
  if (currentUser && currentUser.token) {
    RestangularProvider.setDefaultHeaders({'Authorization': 'Bearer ' + currentUser.token});
  }

  // This is where i should request my refreshed token
  let refreshAccesstoken = function () { /* function here*/};

  // Provided exemple of interceptor inthe README
  RestangularProvider.addErrorInterceptor((response, subject, responseHandler) => {
    if (response.status === 403) {
      refreshAccesstoken()
        .switchMap(refreshAccesstokenResponse => {
          return response.repeatRequest(response.request);
        })
        .subscribe(
          res => responseHandler(res),
          err => subject.error(err)
        );
      return false;
    }
    return true; 
  });
}

@NgModule({
    imports: [
      ...
      RestangularModule.forRoot([Http], configFunc),
    ]
...
})
export class AppModule { }

So basically i'm trying to do a simple post like this, but I don't know where to put the interceptor and the refresh function.

Restangular.one('token').post('refresh',{
      'refresh_token' : currentUser.refresh_token,
    })

Any idea how to solve this ?

Duplicate part of angular

When I see ng2-restangular/dist/umd/ng2-restangular.js it is contains parts of angular framework.
Example:

XHRConnection,
CookieXSRFStrategy,
XHRBackend,
RequestOptions,
Request
.....

I use browserify, which can not dedupe this parts and caouse many anomaly like angular/angular#9294

How to access service in app.module?

I have a auth service that I want to access to set some values in restangularInit

export function restangularInit(RestangularProvider, AuthService) {
  RestangularProvider.setBaseUrl('api');
  RestangularProvider.setDefaultHeaders(
    {'Authorization': 'Bearer [replace this :) ]'},
  );
}

can´t find out how to use my AuthService.. it just stays "undefined"..
Any help is appreciated!

Compatible with Angular 2.4.9

I got error:
ng2-restangular.config.js:5 Uncaught TypeError: core_1.InjectionToken is not a constructor
at Object.defineProperty.value (ng2-restangular.config.js:5)
at webpack_require (bootstrap 9ec4341…:52)
at Object. (ng2-restangular.module.js:6)
at webpack_require (bootstrap 9ec4341…:52)
at Object.defineProperty.value (index.js:3)
at webpack_require (bootstrap 9ec4341…:52)
at Object. (app.module.ts:22)
at webpack_require (bootstrap 9ec4341…:52)
at Object. (index.ts:1)
at webpack_require (bootstrap 9ec4341…:52)
at Object. (main.browser.ts:13)
at webpack_require (bootstrap 9ec4341…:52)
at Object. (BehaviorSubject.js from dll-reference vendor_lib:1)
at webpack_require (bootstrap 9ec4341…:52)
at webpackJsonpCallback (bootstrap 9ec4341…:23)
at main.bundle.js:2

How to return observable response (CustomGET) for resolver?

Hi, guys! I need some help! In my previous project i used Http provider out of box and all was good, but now i'm encountered with some problems.

I tried to do request, for example:
this.restangular.one('countries').customGET().map((response: any) => response);

But it return AnonymousSubject.
image

When i used standard Http provided by Angular 2 for get requests it returns Observable like this one:
image

How can i do CustomGET request that return Observable object?

Thanks for help and sorry for my bad English :)

Error on new Ionic 2 RC3 with AoT compiler

Hello,

I am trying to use it with Ionic 2, I got the following error in the ionic build android command.

Error: Error encountered resolving symbol values statically. Function calls are not supported. Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function (position 7:10 in the original .ts file), resolving symbol RestangularFactory in .. /node_modules/ng2-restangular/dist/esm/src/ng2-restangular.config.d.ts, resolving symbol RestangularModule in .. node_modules/ng2-restangular/dist/esm/src/ng2-restangular.module.d.ts

Regards.

Question about model classes

Is there any support for using ng2-restangular with existing TypeScript model classes?

Say I already have TypeScript model classes for things like Account and User and I would like to use restangular to manage the server interaction but still use my existing models. Is that possible, or is it planned if it's not?

I'd love to use restangular (I used the old one for a while with angular 1.x and loved it) but not being able to use my own model classes would be a blocker.

Subscriber never gets isStopped or closed true.

Hello,

I am trying to implemente angular2-busy, but I found that the Subscriber using customPOST never got closed or isStopped.

image

In the image for the first subscriber I am using customPOST, and the second one is from http post (angular 2 http).

not sure what is going on.

Regards.

browser says 401, restangular says 0

I want to run some functions if I get a 401.
in my code I get response.status as "0" when the browser returns a 401..

RestangularProvider.addErrorInterceptor((response, subject, responseHandler) => { console.log(response); if (response.status === 401) { console.log('401'); } });

How to set Bearer token

I have a service where I have a getToken() method.
getToken uses localforage to get it form localstorage (https://localforage.github.io/localForage/#data-api-getitem)

getToken() {
  return localforage.getItem('auth', function (err, value) {
    return _.result(value, ['access_token']);
  });
}

But I have the problem where the componets I have makes requests before the token is set.
I have tried to use RestangularProvider.addFullRequestInterceptor but have the same issue there.

So what is the proper way to first get the token from the API and then set it to the defaultHeaders?

How to access service in export function restangularInit

I have a service (AuthService) that I need to access in my restangularInit function (in my app.module.ts) but I dont know how I cant get access to it.

import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';
    import { FormsModule } from '@angular/forms';
    import { HttpModule } from '@angular/http';
    import { MaterialModule } from '@angular/material';
    import { FlexLayoutModule } from "@angular/flex-layout";
    import { RestangularModule } from 'ng2-restangular';

    // Components
    import { AppComponent } from './app.component';
    import { ProductComponent } from './components/product/product.component';

    // Services
    import { AuthService } from './services/auth.service';

    export function restangularInit(RestangularProvider, AuthService) {
      console.log(AuthService); // this is undefined
      let token = AuthService.getToken(); //This is what I want to do
      RestangularProvider.setBaseUrl('api');
      RestangularProvider.setDefaultHeaders(
        {'Authorization': 'Bearer ' + token},
      );
    }

    @NgModule({
      declarations: [
        AppComponent,
        ProductComponent
      ],
      imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        MaterialModule,
        FlexLayoutModule,
        RestangularModule.forRoot(restangularInit)
      ],
      providers: [
        AuthService
      ],
      entryComponents: [ProductComponent],
      bootstrap: [AppComponent]
    })
    export class AppModule { }

.get/.customGET and FormData

Hi, guys! Today i've been stuck with next moment: when i used .post() method with formData (i`m creating FormData object through URLSearchParams adapter) all has been ok, but when i'm trying to pass formData object to queryParams in .get() or .customGET() method it doesn't work in expected way and i have my URLSearchParams adapter in query params.

For example:
i need to do some request with next filters:
filter[type] = 1
filter[currency] = 1

POST with number response

Hi,

My POST service response is just a number (ie 1234). When I use restangular post method, I get an error Cannot create property ‘route’ on number ’1234’. I assume that Restangular tries to decorate a Javascript number and fails.

Is a number a valid response for a REST service and should Restangular be fixed for this kind of response ? If I fix the service and return nothing, Restangular post method works perfectly. Should I stick on this solution ?

Restangular 0.1.30
angular 2.4.10

Typings Typings Typings

Would be amazing to have more verbose typings for this library due to Restangular's unique method chaining as well as other things.

About the SHOULD contain a array business :)

Most of the API´s I have been using lately all deliver a json object at the top level
Readning here: http://jsonapi.org/format/#fetching
we can see the following statement:

A JSON object MUST be at the root of every JSON API request and response containing data. This object defines a document’s “top level”.

But when using restangular it states that it should be an array.. why is that?
I´m not saying that this is wrong.. just want to understand why.

Note: I already use RestangularProvider.addResponseInterceptor to handle this for me so I have no real issue.

.Subscribe function never gets invoked

Hi,
When using version 0.0.35 , the Url hits the server and the details can be seen in the network tab. But the .subscribe function doesnot get invoked later ?

ngOnInit()
{
console.log('trying to fetch data....');
this.restangular.all('users').getList()
.subscribe((data: any) => {
console.log('data is fetched....');
console.log(data[0].id);
})

}

withCredentials support

currently i couldn't make the following work

    RestangularProvider.setDefaultHttpFields({ withCredentials: true });

by looking at the request creation,

    let requestOptions = new RequestOptions({

seems we are missing withCredentials: true as one of the options. I just wonder if this is the case, since without it, i couldn't get 'set-cookie' work

Observable and Http errors

Can anybody explain me the mechanism of error handling? For example, I have 2 subscribers on one observer

  let observable = this.authService.signIn(formGroup.value.email, formGroup.value.password);
  
  // 1st subscriber
  observable.subscribe((response: SignInResponse) => {
    console.log('First - Success');
  }, () => {
    console.log('First - Error');
  }, () => {
    console.log('First - Finally');
  });
  
  // 2nd subscriber
  observable.subscribe((response: SignInResponse) => {
    console.log('Second - Success');
  }, () => {
    console.log('Second - Error');
  }, () => {
    console.log('Second - Finally');
  });`

If I get 400 from the server - both error messages First - Error, Second - Error appears as expected,
but if I remove error and finally callback for the first subscriber as

  let observable = this.authService.signIn(formGroup.value.email, formGroup.value.password);
  
  observable.subscribe((response: SignInResponse) => {
    console.log('First - Success');
  });

  observable.subscribe((response: SignInResponse) => {
    console.log('Second - Success');
  }, () => {
    console.log('Second - Error');
  }, () => {
    console.log('Second - Finally');
  });

I don't get the error callback of the second subscriber

problem with RestangularModule.forRoot(RestangularProvider

Trying to do
RestangularModule.forRoot((RestangularProvider) =>

from manual and getting error:

ERROR in Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the func
tion or lambda with a reference to an exported function (position 18:31 in the original .ts file), resolving symbol AppModul
e in ..../src/app/app.module.ts

Module Error on QuickStart

Im using Angular-cli's implemantion of webpack:

➜  web git:(master) ✗ ng -v

                             _                           _  _
  __ _  _ __    __ _  _   _ | |  __ _  _ __         ___ | |(_)
 / _` || '_ \  / _` || | | || | / _` || '__|_____  / __|| || |
| (_| || | | || (_| || |_| || || (_| || |  |_____|| (__ | || |
 \__,_||_| |_| \__, | \__,_||_| \__,_||_|          \___||_||_|
               |___/
angular-cli: 1.0.0-beta.26
node: 6.9.1
os: darwin x64
@angular/common: 2.3.1
@angular/compiler: 2.3.1
@angular/core: 2.3.1
@angular/forms: 2.3.1
@angular/http: 2.3.1
@angular/platform-browser: 2.3.1
@angular/platform-browser-dynamic: 2.3.1
@angular/router: 3.3.1
@angular/compiler-cli: 2.3.1

Im trying to follow your quickstart guide and get the following:

ERROR in Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function, resolving symbol CONFIG_OBJ in /Users/jmurphy/projects/business/web/node_modules/ng2-restangular/dist/esm/src/ng2-restangular.module.d.ts, resolving symbol RestangularModule in /Users/jmurphy/projects/business/web/node_modules/ng2-restangular/dist/esm/src/ng2-restangular.module.d.ts, resolving symbol AppModule in /Users/jmurphy/projects/business/web/src/app/app.module.ts, resolving symbol AppModule in /Users/jmurphy/projects/business/web/src/app/app.module.ts

export function httpConfigurator(restangular: Restangular) {
  return restangular.withConfig((RestangularConfigurer) => {
    RestangularConfigurer.setBaseUrl('https://randomuser.me/api/');
  });
}

...
RestangularModule.forRoot(httpConfigurator),

Error on Ionic build android --prod

Restangualr Breaks while Ionic build android --prod.

Info:
Angular version :2.2.1
ng2-restangular version: 0.1.7

npm ERR! Linux 4.4.0-57-generic
npm ERR! argv "/usr/bin/nodejs" "/usr/bin/npm" "run" "ionic:build" "--" "--prod"
npm ERR! node v4.2.6
npm ERR! npm v3.5.2
npm ERR! code ELIFECYCLE
npm ERR! ionic-hello-world@ ionic:build: ionic-app-scripts build "--prod"
npm ERR! Exit status 1

Stack Trace:

[19:22:56] build prod failed: Error encountered resolving symbol values statically. Function calls are not supported.
Consider replacing the function or lambda with a reference to an exported function (position 7:10 in the
original .ts file), resolving symbol RestangularFactory in
/home/naveen/workspace/Navi/phonegap/ionicauth2/node_modules/ng2-restangular/dist/esm/src/ng2-restangular.config.d.ts,
resolving symbol RestangularModule in
/home/naveen/workspace/Navi/phonegap/ionicauth2/node_modules/ng2-restangular/dist/esm/src/ng2-restangular.module.d.ts,
resolving symbol AppModule in /home/naveen/workspace/Navi/phonegap/ionicauth2/src/app/app.module.ts,
resolving symbol AppModule in /home/naveen/workspace/Navi/phonegap/ionicauth2/src/app/app.module.ts
[19:22:56] ionic-app-script task: "build"
[19:22:56] Error: Error encountered resolving symbol values statically. Function calls are not supported. Consider
replacing the function or lambda with a reference to an exported function (position 7:10 in the original .ts
file), resolving symbol RestangularFactory in
/home/naveen/workspace/Navi/phonegap/ionicauth2/node_modules/ng2-restangular/dist/esm/src/ng2-restangular.config.d.ts,
resolving symbol RestangularModule in
/home/naveen/workspace/Navi/phonegap/ionicauth2/node_modules/ng2-restangular/dist/esm/src/ng2-restangular.module.d.ts,
resolving symbol AppModule in /home/naveen/workspace/Navi/phonegap/ionicauth2/src/app/app.module.ts,
resolving symbol AppModule in /home/naveen/workspace/Navi/phonegap/ionicauth2/src/app/app.module.ts
Error: Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function (position 7:10 in the original .ts file), resolving symbol RestangularFactory in /home/naveen/workspace/Navi/phonegap/ionicauth2/node_modules/ng2-restangular/dist/esm/src/ng2-restangular.config.d.ts, resolving symbol RestangularModule in /home/naveen/workspace/Navi/phonegap/ionicauth2/node_modules/ng2-restangular/dist/esm/src/ng2-restangular.module.d.ts, resolving symbol AppModule in /home/naveen/workspace/Navi/phonegap/ionicauth2/src/app/app.module.ts, resolving symbol AppModule in /home/naveen/workspace/Navi/phonegap/ionicauth2/src/app/app.module.ts
at positionalError (/home/naveen/workspace/Navi/phonegap/ionicauth2/node_modules/@angular/compiler-cli/src/static_reflector.js:595:18)
at simplifyInContext (/home/naveen/workspace/Navi/phonegap/ionicauth2/node_modules/@angular/compiler-cli/src/static_reflector.js:473:27)
at StaticReflector.simplify (/home/naveen/workspace/Navi/phonegap/ionicauth2/node_modules/@angular/compiler-cli/src/static_reflector.js:478:22)
at StaticReflector.annotations (/home/naveen/workspace/Navi/phonegap/ionicauth2/node_modules/@angular/compiler-cli/src/static_reflector.js:60:36)
at NgModuleResolver.resolve (/home/naveen/workspace/Navi/phonegap/ionicauth2/node_modules/@angular/compiler/bundles/compiler.umd.js:14261:46)
at CompileMetadataResolver._loadNgModuleMetadata (/home/naveen/workspace/Navi/phonegap/ionicauth2/node_modules/@angular/compiler/bundles/compiler.umd.js:14646:45)
at CompileMetadataResolver.getUnloadedNgModuleMetadata (/home/naveen/workspace/Navi/phonegap/ionicauth2/node_modules/@angular/compiler/bundles/compiler.umd.js:14636:23)
at addNgModule (/home/naveen/workspace/Navi/phonegap/ionicauth2/node_modules/@angular/compiler/bundles/compiler.umd.js:12944:43)
at /home/naveen/workspace/Navi/phonegap/ionicauth2/node_modules/@angular/compiler/bundles/compiler.umd.js:12957:16
at Array.forEach (native)

model in services to decouple restangular

I want to create services to fetch products from a api and then map it to my own product model to make it easy to switch between different API´s

This is the current service:

getProducts(category) {
      let products = this.restangular.all("products").customGET();
  }

So that´s simple and works. Now I would like to map the response data to match my product model.
What approach would you recommend?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.