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;
      }
    );
9
  • Is the json file in your assets folder? Or where are you reading it from? Commented Mar 6, 2020 at 6:47
  • yes, in assets folder Commented Mar 6, 2020 at 6:48
  • So why don't you just import it and use it as an object? Commented Mar 6, 2020 at 6:49
  • please tell , as I am new to angular Commented Mar 6, 2020 at 6:50
  • Check this stackoverflow.com/questions/47206924/… Commented Mar 6, 2020 at 6:52

1 Answer 1

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 }}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.