Coder Social home page Coder Social logo

Comments (3)

troyanskiy avatar troyanskiy commented on June 19, 2024 1

Hi!
I did some tests with getHeaders and for me it was called once, but it called for every request.
Probably in your case it calls several times refreshToken per page load if you have several api requests and since the token is not valid it will call refreshToken several times. I think you should somehow block other requests and wait until refreshToken will be executed.

Usually i'm implementing AuthGuard resource class which blocks all requests until get config request is not done yet.

import { Request, Response } from '@angular/http';
import { Resource } from 'ng2-resource-rest';
import { Observable, Subscriber } from 'rxjs';
import { AppConfigResource } from './appConfig.resource';
import { IAppConfigEvent, TAppConfigEvent } from '../interfaces/common.interfaces';
import { AuthService, ConfigService } from '../services/index';

export class AuthGuardResource extends Resource {

  private deferredQ: Subscriber<any>[] = [];
  private configListenerSet: boolean = false;

  getHeaders(): any {
    let headers = super.getHeaders();

    headers = AuthService.instance.extendHeaders(headers);

    return headers;
  }

  responseInterceptor(observable: Observable<any>, request?: Request): Observable<any> {

    // Checking is config has been loaded
    if (ConfigService.instance.isLoaded || this instanceof AppConfigResource) {

      return Observable.create((subscriber: Subscriber<any>) => {

        observable.subscribe(
          (res: Response) => {
            if (res.headers) {
              let newToken: string = res.headers.get('X-C3-AUTH-TOKEN');
              if (newToken) {
                AuthService.instance.token = newToken;
              }
            }

            subscriber.next((<any>res)._body ? res.json() : null);
          },
          (error: Response) => {
            if (error.status === 401) {
              AuthService.instance.token = null;
            }
            //console.warn('BaseResource request error', error, request);
            subscriber.error(error);
          },
          () => subscriber.complete()
        );

      });

    }

    // Creating deferred observable
    let retObservable = Observable.create((observer: Subscriber<any>) => {
      this.deferredQ.push(observer);
    }).flatMap(() => this.responseInterceptor(observable));

    this.startConfigListener();

    return retObservable;

  }


  private startConfigListener() {
    if (this.configListenerSet) {
      return;
    }

    this.configListenerSet = true;

    let subscr = ConfigService.instance.eventBus
      .filter((event: IAppConfigEvent) => event.type === TAppConfigEvent.loadSuccess)
      .subscribe(
        () => {
          if (ConfigService.instance.isLoaded) {
            subscr.unsubscribe();
            this.executeDeferred();
          }
        }
      );
  }

  private executeDeferred() {
    let deferredQ = this.deferredQ;
    this.deferredQ = [];
    deferredQ.forEach((deferred) => {
      deferred.next();
      deferred.complete();
    });
  }
}

from ngx-resource.

troyanskiy avatar troyanskiy commented on June 19, 2024

Hello.
It's strange, it should be called once.
I will check that. Thank you!

from ngx-resource.

JulioWar avatar JulioWar commented on June 19, 2024

Sorry @troyanskiy, my mistake. 😞
I had not realized that I was doing two queries.
I was looking in the wrong place.

Thanks for your Answare.

from ngx-resource.

Related Issues (20)

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.