How to remove hardcoded get url from angular?

Viewed 542

I am using the rest api to get the data. For that i am giving the hardcoded url. How to remove this one?

Here is service.ts :-

getAllEmployees(): Observable<Employee[]>{
        return this._httpService.get("http://localhost:8080/EmpProject/getAllEmployees")
        .map((response: Response) => response.json())
        .catch(this.handleError);
    }

I wan to remove this http://localhost:8080 hardcode value.

2 Answers

You can use the environment files for this. For development environment add your URL to the file environment.ts. You can find it in src > environments.

export const environment = {
  production: false,
  baseUrl: 'http://localhost:8080' 
};

You can use it like this

import { environment } from '../../environments/environment';


@Injectable()
export class MyService {  
  
  constructor(private httpClient: HttpClient) { }

  getData(id: number) {
    let url = environment.baseUrl + '/datas/1';
    return this.httpClient.get<JSON>(url);
  }
}

The same thing for production environment, but you need to change the file environment.prod.ts

Related