troyanskiy / ngx-resource

Resource (REST) Client for Angular 2
http://troyanskiy.github.io/ngx-resource/
200 stars 46 forks source link

ngx-resouce and angular2-token #138

Closed rbetancor closed 7 years ago

rbetancor commented 7 years ago

I'm using angular2-token in a proyecto to handle all the auth-related stuff against a rails5 backend.

Does anyone knows how could I wrapt the Resouce Http use another Http client, I'm trying to use the wrapper that Angular2TokenService provides, so it will take care off all token management.

troyanskiy commented 7 years ago

In you app module try to use your custom http provider

{ provide: Http, useClass: MyCustomHttp }
rbetancor commented 7 years ago

@troyanskiy the problem is that angular2-token wraps the method calls to .get .post, etc. ... it only offer me to inject the service and then use like this.tokenService.get(...) ... So I think that just following and example I found will be easier ... just with a RescClient class that extends Resource and overloading $getHeaders and $responseInterceptor, so I could setup the token headers and check if the token changed during the response phase.

import { Resource } from 'ngx-resource';
import { environment } from '../environments/environment';
import { Headers } from '@angular/http';

export class RestClient extends Resource {

  $getHeaders(methodOptions?: any): any {
    // headers: this.tokenService.currentAuthHeaders // TokenService return the valid headers
    if (methodOptions.auth) {
      return new Headers({
                'access-token': localStorage.getItem('accessToken'),
                'client':       localStorage.getItem('client'),
                'expiry':       localStorage.getItem('expiry'),
                'token-type':   localStorage.getItem('tokenType'),
                'uid':          localStorage.getItem('uid')
            });
    }
  }

  $getUrl(methodOptions?: any): sting | Promise<string> {
    let resPath = super.$getUrl();
    return environment.token_auth_config.apiBase + resPath;
  }

  $responseInterceptor(observable: Observable<any>, request: Request, methodOptions?: any): Observable<any> {
    return Observable.create((subscriber: Subscriber<any>) => {
      observable.subscribe(
        (res: Response) => {
          if (res.headers) {
            const newToken: string = res.headers.get('access-token');
            if (newToken != localStorage.getItem('accessToken')) {
              localStorage.setItem('accessToken', newToken);
            }
          }
          const body = (<any>res)._body;
          subscriber.next(body ? res.json() : null);
        },
        (error: Response) => {
          // I also made a layer to parse errors
          subscriber.error(new Error(error.statusText));
        },
        () => subscriber.complete()
      );
    });
  }
}
troyanskiy commented 7 years ago

Hello all.

I've released some kind of beta of new library which is called rest-core + rest-ngx. Please check them rest-core and rest-ngx.

It works the way like ngx-resource but has a lot of breaking changes. Something was removed or simplified.

I've migrated all my projects to the new library. If you wish to switch to HttpClient or use some other http handlers like fetch try to migrate your projects to the lib.

Bugs and help requests are welcome in corresponding repos.

Thanks!

PS: Since ngx-resource is no longer supported by me, closing the issue.