Home > Software design >  read jsonfile typescript angular
read jsonfile typescript angular

Time:01-03

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

CodePudding user response:

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.

CodePudding user response:

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);
  • Related