Dignity Dignity
Dignity Dignity

Reputation: 151

How to set json file to object's array in Angular

how to set json file to my "Client" object's array? I have json, which looks like this:
Clients.json

{
   "clients": [
   {
      "firstName": "nameA",
      "lastName": "lastA",
      "doctorsName": "domm",
      "procedure": "consultation",
      "registrationDate": "new Date(2019, 10, 12)",
      "isAlreadyServed": "false"
   },
   {
      "firstName": "nameB",
      "lastName": "lastB",
      "doctorsName": "domm",
      "procedure": "procedureA",
      "registrationDate": "new Date(2019, 10, 12)",
      "isAlreadyServed": "false"
   },
   {
      "firstName": "nameC",
      "lastName": "lastC",
      "doctorsName": "doctorA",
      "procedure": "procedureC",
      "registrationDate": "new Date(2019, 10, 12)",
      "isAlreadyServed": "false"
   },

   ...
   ...
   ...


And how can I set it to object's array Client.service.ts

clients: Client[] = this.http.get('path.Clients.json') // ??

Upvotes: 0

Views: 3012

Answers (2)

nash11
nash11

Reputation: 8690

Since your data is in the client-side as a JSON file. Though you can use HttpClient, here is another solution for the same.

You can directly import the JSON as a constant and assign it to clients as of TS 2.9 (docs).

import Clients from 'path/to/client/json';

clients: ClientsJson = Clients;

where the ClientsJson interface would look like this.

export interface ClientsJson {
    clients: Client[];
}

export interface Client {
    firstName: string;
    lastName: string;
    doctorsName: string;
    procedure: string;
    registrationDate: Date;
    isAlreadyServed: boolean;
}

Here is a working example on StackBlitz.

Upvotes: 4

user4717662
user4717662

Reputation:

You first need to define an interface that matches your object structure:

public interface ClientConfiguration {
    firstName: string;
    lastName: string;
    doctorsName: string;
    // And so on...
}

Then, just like the code you have shown, you need to type the http.get method in order to obtain the correct output.

public getConfiguration(): Observable<Array<ClientConfiguration>> {
    return this.http.get<Array<ClientConfiguration>>('path/to/client/json');
}

Since my getConfiguration() method returns an observable, you will need to subscribe to it in your components or services:

@Component({ ... })
export class MyComponent implements OnInit {
    public ngOnInit(): void {
        this.getConfiguration().subscribe(result: Array<ClientConfiguration> => {
             this.clientConfiguration = result;
        });
    }

    public getConfiguration(): Observable<Array<ClientConfiguration>> {
        return this.http.get<Array<ClientConfiguration>>('path/to/client/json');
    }
}

You can read more here about HttpClient at Angular's official documentation: https://angular.io/guide/http

Hope it helps.

Upvotes: 1

Related Questions