voliva / angular2-interceptors

79 stars 20 forks source link

Cannot prepend url before to Interceptor #26

Closed alvarosabu closed 7 years ago

alvarosabu commented 7 years ago

Hi Victor,

I having an issue trying to do a Server Url Interceptor to prepend the Api url (http://localhost:5678/api) to every Http request, I debug and its passing trough the Interceptor but the Post request use the actual dev server url (http://localhost:7682) where the app is running so it means that is not adding the new url created in the interceptor to the post request.

Here is my setup:

Login.module.ts

import { NgModule }      from '@angular/core';
import { CommonModule }  from '@angular/common';
import { FormsModule }   from '@angular/forms';
import {
  ModalModule
} from 'ng2-bootstrap';
import {
  HttpModule,
  XHRBackend,
  RequestOptions
} from '@angular/http';
import {
  InterceptorService,
  Interceptor,
  InterceptedRequest,
  InterceptedResponse
} from 'ng2-interceptors';

import { AuthService }         from './auth.service';
import { AuthGuard }         from './auth.guard';
import { LoginComponent } from './login.compontent';
import { ServerURLInterceptor } from './serverURLInterceptor.service';

export function interceptorFactory(
    xhrBackend: XHRBackend,
    requestOptions: RequestOptions,
    serverURLInterceptor: ServerURLInterceptor,
    authService: AuthService

) { // Add it here
  let service = new InterceptorService(xhrBackend, requestOptions);
  service.addInterceptor(serverURLInterceptor);
  return service;
}
@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    HttpModule,
    ModalModule
  ],
  declarations: [
    LoginComponent
  ],
  providers: [
    AuthGuard,
    ServerURLInterceptor,
    AuthService,
      {
        provide: InterceptorService,
        useFactory: interceptorFactory,
        deps: [
          XHRBackend,
          RequestOptions,
          ServerURLInterceptor
         ]
      },

  ],
})
export class LoginModule { }

ServerUrlInterceptor.ts

import { Injectable } from '@angular/core';
import {
    InterceptorService,
    Interceptor,
    InterceptedRequest,
    InterceptedResponse
} from 'ng2-interceptors';
import {
    XHRBackend,
    RequestOptions,
    RequestMethod
} from '@angular/http';

@Injectable()
export class ServerURLInterceptor implements Interceptor {
    public interceptBefore(request: InterceptedRequest): InterceptedRequest {
/*        let url = localStorage.getItem('restServerUrl') || ''; */
        let url = 'http://localhost:5678/api';
        request.url = url + request.url;
        if (request.options.method === RequestMethod.Post) {
            request.options.headers.set('Content-Type', 'application/json');
        }
        return request;
    }
}

Auth.service.ts

import { Injectable } from '@angular/core';
import { Http, Headers, Response, XHRBackend } from '@angular/http';

import { Credentials } from '../login/credentials';
import { UserService } from '../shared/user.service';
import { Observable, BehaviorSubject, Subject } from 'rxjs';
import {
  InterceptorService
} from 'ng2-interceptors';

@Injectable()
export class AuthService {
  public loggedIn: boolean = false;
  public authToken: string = null;
  public changes: Subject<any> = new BehaviorSubject<any>(false);
  constructor(public http: InterceptorService, public userService: UserService) {
    this.loggedIn = !!localStorage.getItem('auth_token');
  }

  public login(credentials: Credentials) {
    // let url = "http://188.166.149.103:9989/api";
    let headers = new Headers();
    let body = {
        username: credentials.username,
        password: credentials.password
    };
    // headers.append('Content-Type', 'application/json');
    return this.http
      .post(
        '/auth/login',
        JSON.stringify(body),
        { headers }
      )
      .map((res: Response) => {
            let payload = res.json();
            let heads = res.headers;
            this.userService.user = payload;
            let user = JSON.stringify(payload);
            this.authToken = heads.get('Authorization');
            localStorage.setItem('user', user );
            localStorage.setItem('auth_token', this.authToken);
            this.loggedIn = true;
            return user;
       }).catch((error: any) => {
         let err;
         switch (error.status) {
           case 400:
            err = {
              status: 400,
              title: 'Ups!',
              msg: 'User or Password incorrect'
            };
            break;
           case 401:
            err = {
              status: 401,
              title: 'Ups!',
              msg: 'Invalid credentials'
            };
           break;
           default:
         }
         return Observable.throw(err);
        });

  }

...

}
alvarosabu commented 7 years ago

I find out a solution, it haves to do with the ServerUrlInterceptor itself

export class ServerURLInterceptor implements Interceptor {
    public interceptBefore(request: InterceptedRequest): InterceptedRequest {
/*        let url = localStorage.getItem('restServerUrl') || ''; */
        let url = 'http://localhost:5678/api';
        request.url = url + request.url;
        request.options.url = url + request.options.url;
        if (request.options.method === RequestMethod.Post) {
            request.options.headers.set('Content-Type', 'application/json');
        }
        return request;
    }
}

It seems you have to change both request.url and request.option.url for it to work, I will let it here if someone needs it, now is working.