0

I'm using http request to load a json file, but I'm not actually sure where the config file needs to live.

    this.http.get('env.json')
    .map(res => res.json()).catch((error: any, caught: Observable<any>) => {
        console.log('no');
        return Observable.throw(error.json().error || 'Server error');
    }).subscribe(() => {
        console.log('yes');
    });

After running ng serve, there is no dist folder. I don't think I see a directory where items will get copied from into a dist folder.

So where do I put files that my application needs to load with Http?

Pengyy
  • 37,383
  • 15
  • 83
  • 73
BBaysinger
  • 6,614
  • 13
  • 63
  • 132
  • ng serve will not create dist folder because you are running in dev mode. in order to create dist folder run as production mode by passing --prod [ng build --prod] – VithuBati Mar 16 '18 at 01:49

1 Answers1

1

If the env.json need to be bundled into dist folder and deployed with your other compiled source code, you can simply add it to your project's assets folder(any folder in your project will be ok) and also add assets folder at .angular-cli.json's assets array as below:

"assets": [
  "assets",     // any folder in your project which contains the config file will be ok
  ...
],

And for retrieving data of env.json via http, just use it's path as

this.http.get('assets/env.json')
Pengyy
  • 37,383
  • 15
  • 83
  • 73
  • That's cool. Don't know why I haven't encountered this need before. So do I need to add 'assets/' to the request? – BBaysinger Mar 16 '18 at 01:59
  • And is this all the same for the newer HttpClient vs the old Http? – BBaysinger Mar 16 '18 at 02:01
  • @BBaysinger yes, see my updated part about how to retrieve the data. – Pengyy Mar 16 '18 at 02:01
  • @BBaysinger they are the same. But be aware that `http` has been deprecated since angular V5. – Pengyy Mar 16 '18 at 02:03
  • In one project it works, just as you say. In another project, it's not. I'm seeing the error being caught, but not even seeing a request in console for the file. Going insane. – BBaysinger Mar 16 '18 at 02:13
  • @BBaysinger Sorry, I don't know what's difference between your two project, basically it should always work. – Pengyy Mar 16 '18 at 02:21
  • I duplicated the code into a different place in my app, and it works, but I'm still not seeing the request in the console. Kinda hard to debug that way. – BBaysinger Mar 16 '18 at 02:24
  • @BBaysinger the request should be found at `network` tag. – Pengyy Mar 16 '18 at 02:32
  • Yes, I'm looking in the network tab. It doesn't show anything for that file in either Chrome or FF. – BBaysinger Mar 16 '18 at 02:34
  • 1
    I figured it out. The http calls were being diverted because of InMemoryWebApiModule. I would have figured all this out on my own if it weren't for that. Here's how I figured it out: https://stackoverflow.com/questions/39085512/angular2-error-collection-not-found – BBaysinger Mar 16 '18 at 02:53