How to set a default base URL for all API calls in Angular

0 votes
Can you tell me with the help of cod and an example How to set a default base URL for all API calls in Angular?
Feb 26 in Angular by Nidhi
• 10,860 points
36 views

1 answer to this question.

0 votes

In Angular, you can set a default base URL for all API calls using an HTTP Interceptor.

Method : Using HTTP Interceptor (Recommended)

import { Injectable } from '@angular/core';

import { HttpInterceptor, HttpRequest, HttpHandler } from '@angular/common/http';

@Injectable()

export class BaseUrlInterceptor implements HttpInterceptor {

  private baseUrl = 'https://api.example.com/';

  intercept(req: HttpRequest<any>, next: HttpHandler) {

    const modifiedReq = req.clone({

      url: this.baseUrl + req.url

    });

    return next.handle(modifiedReq);

  }

}

Register Interceptor in app.module.ts:

import { HTTP_INTERCEPTORS } from '@angular/common/http';

import { BaseUrlInterceptor } from './base-url.interceptor';

providers: [

  { provide: HTTP_INTERCEPTORS, useClass: BaseUrlInterceptor, multi: true }

]

answered Feb 26 by Kavya

Related Questions In Angular

0 votes
2 answers

How to detect a route change in Angular?

Hii Kartik For Angular 7 someone should write like: this.router.events.subscribe((event: Event) ...READ MORE

answered Apr 22, 2020 in Angular by Niroj
• 82,840 points
29,492 views
0 votes
1 answer

How to create a URL in the controller .NET MVC?

Hello @kartik, If you just want to get ...READ MORE

answered Jul 23, 2020 in Angular by Niroj
• 82,840 points
6,329 views
0 votes
1 answer

How to know tools and bundlers after create a new workspace or a project in angular?

Hello @sajal, When you create projects and workspaces ...READ MORE

answered Aug 6, 2020 in Angular by Niroj
• 82,840 points
1,138 views
0 votes
1 answer

How to pass data from a child component to a parent component in Angular 4?

In Angular 4, passing data from a ...READ MORE

answered Dec 4, 2024 in Angular by Navya
148 views
+1 vote
8 answers

How can I implement process.env in Angular 5 environment?

Users do not have access to process.env ...READ MORE

answered Apr 3, 2018 in DevOps & Agile by DareDev
• 6,890 points
13,452 views
0 votes
1 answer
0 votes
4 answers

ReactJS vs Angular Comparison: Which is better?

Parameters React Angular Type React is a JavaScript library, and it ...READ MORE

answered Jan 7, 2021 in Events & Trending Topics by Focusteck
• 140 points
2,046 views
+4 votes
9 answers

***IMPORTANT*** AngularJS Interview Questions.

Yes, I agree with Omkar AngularJs is ...READ MORE

answered Mar 17, 2019 in Career Counselling by Sharad
• 180 points
3,940 views
0 votes
1 answer
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP