0

I started to learn typescript --angular, I want to read a json file.

my json file look like this :

{
  "nb": "7",
  "extport": "1176",,
  "REQ_EMAIL": "[email protected]",
  "DIGEST": "sha512",
  "password": "@mypassword",
  "ip": "8.8.8.8",
  "name": "@myname",
  "version": "v3.0.2"
}

my component ts code : i tried to create a variable to read my jsonfile :

import { Component, Input, OnInit } from '@angular/core';
import * as param from '../../data/setup.json'

interface Setup {
  number: string;
  port: string;
  email: string;
  password: string;
}

@Component({
  selector: 'app-appareils',
  templateUrl: './appareils.component.html',
  styleUrls: ['./appareils.component.scss']
})
export class AppareilsComponent implements OnInit {

  constructor() {}

  data: Setup[] = param ; 

  ngOnInit(): void {}

}

but i got error on the variable data created : is missing the following properties from type 'Setup[]': length, pop, push, concat, and 29 more.

how i can fix it to use this variable on the html file ?

thank you

1
  • thank you bu i must use Json File Commented Jan 3, 2023 at 14:39

2 Answers 2

2

You don't usually mix up JSON and Typescript like that.

The first obvious reason is that the file extensions are not the same.

The second main reason is that a JSON file is not managed by your transpiler (typescript) and does not have the typings & all associated with it.

Instead, create a .ts file :

export const setupData = {
  nb: '7',
  extport: '1176',
  REQ_EMAIL: '[email protected]',
  DIGEST: 'sha512',
  password: '@mypassword',
  ip: '8.8.8.8',
  name: '@myname',
  version: 'v3.0.2',
};

You can then import it in your code and let typescript infer the type for you (or you can declare the type yourself if you prefer).

But this way, if you ever get a typing error in your data, the transpiler will catch that and warn you, something it currently does not.

Sign up to request clarification or add additional context in comments.

3 Comments

also, data is expecting an array, where it receives an object.
hi, thank you, but i must use a json files in my app
No you don't. It has NEVER been a requirement by anyone. Moreover, JSON stands for "JavaScript Object Notation", so all you really do is adding a name to your JSON value (variable name)
1

json:

{
  "number": "7",
  "port": "1176",,
  "email": "[email protected]",
  "password": "@mypassword"
}

component class:

import jsonData from '../../data/setup.json';

export class AppareilsComponent {
      number: string;
      port: string;
      email: string;
      password: string;
}

let data= Object.assign(new AppareilsComponent(), jsonData);

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.