07 July 2021

Load config.json File In Angular 2+

 


main.ts

2021
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app/app.module';
import { environment } from './environments/environment';

if (environment.production) {
  enableProdMode();
}

let urlPaths = window.location.href.split('/')
function fetchConfig(){
  fetch(urlPaths.join('/')+'/assets/config.json').then((res)=>{
    return res.json();
  }).then((data)=>{
    window['appApiUrl'] = data.apiUrl
    window['appBaseHref'] = data.baseHref
    window['appRootPath'] = urlPaths.join('/')
    platformBrowserDynamic().bootstrapModule(AppModule).catch(err => console.error(err));
  }).catch((err)=>{
    urlPaths.pop()
    fetchConfig()
  })
}
fetchConfig()
api.service.ts
2021
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class ApiService {

  constructor(private http: HttpClient) { }

  get(url): Observable<any> {
    return this.http.get(window['appApiUrl'] + url);
  }
}


0 nhận xét:

Post a Comment

 

BACK TO TOP

Xuống cuối trang