简体   繁体   中英

unable to retrieve json data from assets folder using angular

what i want : i have a config file where it contains some urls in .json file stored in asset folder now instead of loading environments.prod or .ts i want to load my json file config and basing on that i want run my application

what i did

 below is my json file    which i placed  asset folder

{
    "baseUrl": "https://jsonplaceholder.typicode.com/",
    "baseUrl2": "https://reqres.in/api/users"
}

now i created a ConfigServiceService.ts fpr storing config file

public _config: Object;

  constructor(public http:Http) { }

  getData(){
    debugger;
    return this.http.get("./assets/config.json").pipe(map(res =>  res.json()));
  }

after this i create a ServiceProviderService.ts for calling the service file

configData:any;

  constructor(public http:Http,public config:ConfigServiceService) {

   }

  jsonData(){
    debugger;
    return this.configData;
  }

  ngOnInit(){
    debugger;
    this.config.getData().subscribe(res =>{
      console.log(res);
      this.configData = res;
    });


  }

now i am calling the app.component.ts

 title = 'sample';
  constructor(public serv :ServiceProviderService){
    this.serv.jsonData();
  }

now my issue is i am not able to get the json data and if i am putting the logic which is there is ngoninit in ServiceProviderService.ts file if put it in constructor then i am getting undefined

note : here if there are more that once url then each url is distributed to various seperate service file suppose base1 url for 1 service file ans base2 url for another file how can i achieve that

To access the assets folder. Make sure angular.json has a reference under

architect --> build --> options to the directory where the file is stored:

 "assets": [
              "src/favicon.ico",
              "src/assets"
            ],

In Angular only components have lifecycle hooks (like ngOnInit , ngOnDestroy etc), services haven't. In services you should use their constructor instead.

Try giving it an absolute url and it should work

Here, give this a try:

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class ConfigService {

  constructor(private http: HttpClient) { }

  getData() {
    return this.http.get('/assets/config.json');
  }

}

Here's a Working Sample StackBlitz for your ref.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM