0

I'm trying to read a JSON configuration file like this

this.http.get('assets/env/env.json').pipe(map( res => res.json())).pipe(catchError((error: any): any => {
  console.log('Configuration file "env.json" could not be read');
  
  return Observable.throw(error.json().error || 'Server error');
})).subscribe( (envResponse) => {
  endpoint="conf-" + envResponse.env + ".json";
  alert(endpoint);
});

But res.json() shows as error

I'm importing these classes

import { Injectable } from '@angular/core';
import { HttpClient, HttpBackend } from '@angular/common/http';
import { map, catchError } from 'rxjs/operators';
import { Observable } from 'rxjs';

Could you please suggest what I did wrong?

Mine is angular 9

Giannis
  • 1,790
  • 1
  • 11
  • 29
Sandeep Thomas
  • 4,303
  • 14
  • 61
  • 132
  • Is this post what you need ? https://stackoverflow.com/questions/46630893/angular-res-json-is-not-a-function – Alexis Sep 02 '20 at 12:13

2 Answers2

1

I believe you're coming from an older version of Angular/RxJS. In the newer versions, the default responseType is json. So res.json() isn't required anymore.

Try the following

this.http.get('assets/env/env.json').pipe(
  catchError((error: any): any => {...})
).subscribe(
  ...
);

Also you don't need individual pipe() for each RxJS operator. You could include all the operators in a single pipe.

this.http.get('assets/env/env.json').pipe(
  map(res => {
    // transform and return the value
  }),
  tap(res => {
    // perform some side-effects
  }),
  catchError((error: any): any => {
    console.log('Configuration file "env.json" could not be read');
    return throwError(error.error || 'Server error');
  })
).subscribe(
  ...
);

There is also now a RxJS throwError function instead of Observable.throw.

ruth
  • 29,535
  • 4
  • 30
  • 57
1

Instead of using http to retrieve the json you could also set your compilerOptions to

    "resolveJsonModule": true,
    "allowSyntheticDefaultImports": true

And import the json in your ts file

import myJson from './path-to-json/my-json.json';

You can then access it like constant (synchronous), no need for asset or asynchronous http call.


Edit:

As you requested, here how it would look like

First your import (the correct path should differ on your side)

import envJson from '../env/env.json';

Then you can use it so:

  endpoint = "conf-" + envJson.env + ".json";

Please still keep in mind that those compilerOptions are not enabled by default and are required to do this approach.


Please refer to the working stackblitz: https://stackblitz.com/edit/angular-ivy-umoflb?file=src/app/app.component.ts (Also check the tsconfig.ts file for the compilerOptions added)

MoxxiManagarm
  • 8,735
  • 3
  • 14
  • 43