2

I'm building an app in angular 9 and I have a .json file to get data and I want to get first element.

I tried it from take(1), first and single() but none worked.

How can we fetch data from JSON file?

JSON

[
  {
    "username": "test",
    "password": "test",
    "firstName": "User",
    "lastName": "Test"
  },
  {
    "username": "test1",
    "password": "test1",
    "firstName": "User1",
    "lastName": "Test1"
  }
]

Component.ts

this.authenticationService.login()
    .pipe(first())
    .subscribe(
      data => {
      console.log(data)
        if(this.loginModel.username == data.username && this.loginModel.password == data.password){
          localStorage.setItem('currentUser', JSON.stringify(data));
          this.router.navigate([this.returnUrl]);
        }
        else{
          // this.error = error;
          // this.loading = false;
          alert('Please enter correct USERNAME OR PASSWORD');
        }
      },
      error => {
        this.error = error;
        this.loading = false;
      }
    );
Mohamad Mousheimish
  • 1,641
  • 3
  • 16
  • 48
Coding test
  • 23
  • 1
  • 3

1 Answers1

3

Since your json file is in your assets folder, you can import it and use it as an object.

Here's what I do normally:

JSON File

{
   "LayerIds": [0, 1, 2, 3, 4, 5, 7, 8, 11, 20, 21, 22, 23],
   "HiddenLayerIds": [3, 7, 11, 21, 20, 23],
   "DefinitionExpressionColumn": "vertical_order",
   "LevelId": 7,
   "LevelFilterOutFields": "vertical_order, name",
   "SelectedLayerId": 2,
   "LevelDictionary": ["vertical_order", "name"],
   "PathwaysLayerId": 22,
   "GeometryServiceAreaUnit": "square-feet",
   "GeometryServiceLengthUnit": "feet"
}

Service.ts

 import myJson from '../../../assets/json/config.json';

 readConfigFile() {
   return myJson;
 }

Component.ts

ngOnInit() {
   this.mainConfiguration = this.service.readConfigFile();

   // This will print "feet" to the console
   console.log(this.mainConfiguration.GeometryServiceLengthUnit);
}

You can skip the service step and import the json file directly into your component. But since you're using it as an object I think your json file should be like this:

{
 "Users": [
   {
     "username": "test",
     "password": "test",
     "firstName": "User",
     "lastName": "Test"
   },
   {
     "username": "test1",
     "password": "test1",
     "firstName": "User1",
     "lastName": "Test1"
   }]
}

In this way when you import the json file. Try Console.log(importedjson.Users); to see your data.

NOTE: If you built your application and got the following error:

Cannot find module ‘../../assets/SampleJson.json’. Consider using ‘–resolveJsonModule’ to import module with ‘.json’ extension

To remove the above error, in tsconfig.json file under compiler options we need to add resolveJsonModule and esModuleInterop configurations as true as shown below.

{  "compilerOptions": {  "resolveJsonModule": true, "esModuleInterop": true }}
Mohamad Mousheimish
  • 1,641
  • 3
  • 16
  • 48