ngx-jsonapi icon indicating copy to clipboard operation
ngx-jsonapi copied to clipboard

Can't intercept http requests since v3.0.0-dev

Open DeinChristian opened this issue 3 years ago • 5 comments

We can't intercept requests in version 3.0.0-dev anymore (Angular). That works perfectly in 2.2.3.

example interceptor:

@Injectable({
  providedIn: 'root'
})
export class TokenInterceptor implements HttpInterceptor {

  constructor(private authService: OAuthService) {
  }

  intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
    if (this.authService.hasValidAccessToken()) {
      request = request.clone({
        setHeaders: {
          Authorization: 'Bearer ' + this.authService.getAccessToken()
        }
      })
    }

    return next.handle(request)
  }

}

DeinChristian avatar Nov 11 '21 20:11 DeinChristian

Fix or riot!

joulewei avatar Nov 11 '21 20:11 joulewei

Same problem, any solution ??

niskah-energies avatar Nov 27 '21 11:11 niskah-energies

it happens me too

eduardo-r-web avatar Dec 24 '21 22:12 eduardo-r-web

Someone have any solution ??

niskah-energies avatar Apr 12 '22 16:04 niskah-energies

Found a solution. The problem is that this library use axios http client and HttpInterceptor not work.

I use a Service derived class like this one and it works.

axios-authentication.service.ts

import { Injectable } from '@angular/core';
import { Resource, Service, } from 'ngx-jsonapi';
import axios from 'axios';

@Injectable({
  providedIn: 'root'
})
export abstract class AxiosAuthenticatedService<R extends Resource = Resource> extends Service<R> {

  constructor() {
    super();
    axios.interceptors.request.use(
      function (request) {
         request.headers = {
          'Authorization': 'Bearer ' + YOUR TOKEN HERE
        };
        console.debug('axios interceptor-- ', request);
        return request;
      }
    );
  }}

and use this one to your resources services like this:

import { Injectable } from '@angular/core';
import { Service, } from 'ngx-jsonapi';
import { User } from './users.resource';
import { AxiosAuthenticatedService } from '@app/core/services/axios-authentication/axios-authentication.service';

@Injectable({
    providedIn: 'root'
  })
export class UsersService extends AxiosAuthenticatedService<User> {
    public resource = User;
    public type = 'users';
    public collections_ttl = 1;
}

niskah-energies avatar Apr 26 '22 14:04 niskah-energies