reyesoft / ngx-jsonapi

JSON API client library for Angular 5+ 👌 :: Production Ready 🚀
https://ngx-jsonapi.reyesoft.com/
MIT License
101 stars 52 forks source link

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

Open DeinChristian opened 3 years ago

DeinChristian commented 3 years ago

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)
  }

}
joulewei commented 3 years ago

Fix or riot!

niskah-energies commented 2 years ago

Same problem, any solution ??

eduardo-r-web commented 2 years ago

it happens me too

niskah-energies commented 2 years ago

Someone have any solution ??

niskah-energies commented 2 years ago

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;
}