Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Base URL in Angular App with .Net core

I have developed few angular app with .NET Core , but every time Angular app is separate and .NET Core API is separate .

Now I am developing Angular app using inbuilt Angular template which include API in the same project.

I used to call api with full url (by defining base url as http://portNumber: in a service) but in this inbuilt template this is what I get

    export class FetchDataComponent {
  public forecasts: WeatherForecast[];

  constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
    http.get<WeatherForecast[]>(baseUrl + 'api/SampleData/WeatherForecasts').subscribe(result => {
      this.forecasts = result;
    }, error => console.error(error));
  }
}

its a inbuilt component comes with angular template

Here its written as

http.get<WeatherForecast[]>(baseUrl + 'api/SampleData/WeatherForecasts')

After some searching I found a method getBaseUrl() in main.ts with a constant providers as

   export function getBaseUrl() {
      return document.getElementsByTagName('base')[0].href;
    }
const providers = [
  { provide: 'BASE_URL', useFactory: getBaseUrl, deps: [] }
];

Now can someone explain me how Base Url from here got there in components as @Inject('BASE_URL') without sharing it in a service ?

in angularJS I used to the same with the help of @url.action

$http({
        url: "@Url.Action("Action", "Controller")",
        params: { StaffCode: $scope.staffid },
        method: "GET",
     }) 

Can we do this in angular 5 too ? and how is value of 'BASE_URL' is getting shared without creating a service ??

like image 679
Tanwer Avatar asked Aug 02 '18 05:08

Tanwer


1 Answers

If you open your main.ts file, you will find a function and a provider like this:

export function getBaseUrl() {
  return document.getElementsByTagName('base')[0].href;
}

const providers = [
  { provide: 'BASE_URL', useFactory: getBaseUrl, deps: [] }
];

Notice how the provider is getting the value from the useFactory. And then you will see that using that provider, the main module is being generated:

platformBrowserDynamic(providers).bootstrapModule(AppModule);

And now the provider is injected in your component

constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) {
}

You can learn more about providers here

like image 57
Anup Sharma Avatar answered Sep 28 '22 16:09

Anup Sharma