How to declare a javascript array that will receive a JSON array

Asked

Viewed 349 times

0

Given the interface:

export interface Pergunta {
    id: number
    titulo: string
    opcoes:[]
}

I want the options array to receive its options array:

{
    "id": "1",
    "titulo": "Qual o seu comportamento em relação aos seus investimentos?",
    "opcoes": [
      {
        "description": "Preservar meu dinheiro sem correr risco"
      },
      {
        "description": "Ganhar mais dinheiro, assumindo riscos moderados"
      },
      {
        "description": "Ganhar mais dinheiro, assumindo riscos agressivo"
      }
    ]
  },

2 answers

2


export interface Pergunta {
    id: number;
    titulo: string;
    opcoes: Opcao[];
}

export interface Opcao {
    description: string;
}

This would be the most correct way to receive your data

  • Yes, you are declaring a numeric value as String.... @Marcus Dacorréggio is correct.

  • Marcus pq a public opcoes: Array<Typodeopcoes>; would be wrong?

  • @How I call this array options in question array *ngfor ?

  • If you are using Angular 2+ you can call using *ngFor="let opcao of pergunta.opcoes"

  • Type <Section class="content"> <div class="Row"> <div *ngFor="Let question of questions" class="col-Sm-6 col-Xs-12"> <app-question [question]="></app-question> </div> </div> </Section>

  • Inside of your Component app-pergunta you will probably have the app-pergunta-opcao or something, in which you will use *ngFor I passed above

  • @Tiagotiede I believe that for Angular to make the object deserialize the Array would not serve, would have to be TipoDeOpcoes[]

  • I understand. The strange thing that I made a pocket and it was without stress here. Well the important thing is to learn and help the friend :D

Show 3 more comments

0

I believe the best solution is for you to type the attribute array options. In some cases when you don’t do this process, you can use a array of any. For example:

public opcoes: Array<any>;

However I believe that the best solution to your problem would be something like this:

export interface Pergunta {
    public id: number
    public titulo: string;
    public opcoes: Array<TipoDeOpcoes>;   } 

    export interface TipoDeOpcoes {
            public description: string   
}
  • ai gives me error questionscomponent.html:5 ERROR Error: Invalidpipeargument: '[Object Object],[Object Object],[Object Object]' for pipe 'Asyncpipe'

Browser other questions tagged

You are not signed in. Login or sign up in order to post.