Batsheva
Batsheva

Reputation: 669

Angular4 move from Http to HttpClient - use credentials

We were using HttpModule in angular.

Now we moved to HttpClient as we heard it is better to use it.

All is working fine, BUT - when we used HttpModule we had this piece of code to make chrome send the credentials to the server.

constructor(private http:Http){
  let _build = (<any>this.http)._backend._browseXHR.build;
  (<any>this.http)._backend._browseXHR.build = () => {
       let _xhr = _build();
       _xhr.withCredentials = true;
       return (_xhr);
       };
}

We had to write this only one time in the first service, and all our services were using credentials.

Now we are unable to "convert" this code if we are using HttpClient.

We know we can send in each call the withCredentials:true, but we want something like what we had, that one place is enough for all calls.

What is the parallel code to the above if using HttpClient?

Upvotes: 2

Views: 3524

Answers (1)

Batsheva
Batsheva

Reputation: 669

So, in the end we just created a base service that all the services are using this one.

Base Service:

@Injectable()
export class BaseService{
   options:any;

   constructor(private http:HttpClient){
       this.options = new HttpHeaders().set('Content-Type', 'application/json');
   }

   get(url){
      return this.http.get(url,{withCredentials:true})
           .catch(err => err);
   }

   post(url, obj){
      return this.http.post(url, obj, {headers: this.options, withCredentials:true})
           .catch(err => err);
   }
}

Example to use of base service in a service:

@Injectable()
export class CarService{

   constractor(private baseService:BaseService){}

   getCarDetails(carNumber:number){
       let url = `${BASE_URL}/GetCar/${carNumber}`;
       return this.baseService.get(url);
   }

   updateCar(carDetails:Car){
       let url = `${BASE_URL}/UpdateCar`;
       return this.baseService.post(url, carDetails);
   }
}

Upvotes: 1

Related Questions