Angular 2 declaring an array of objects

前端 未结 7 2073
-上瘾入骨i
-上瘾入骨i 2020-12-13 08:48

I have the following expression:

public mySentences:Array = [
    {id: 1, text: \'Sentence 1\'},
    {id: 2, text: \'Sentence 2\'},
    {id: 3,         


        
相关标签:
7条回答
  • 2020-12-13 09:44

    Another approach that is especially useful if you want to store data coming from an external API or a DB would be this:

    1. Create a class that represent your data model

      export class Data{
          private id:number;
          private text: string;
      
          constructor(id,text) {
              this.id = id;
              this.text = text;
          }
      
    2. In your component class you create an empty array of type Data and populate this array whenever you get a response from API or whatever data source you are using

      export class AppComponent {
          private search_key: string;
          private dataList: Data[] = [];
      
          getWikiData() {
             this.httpService.getDataFromAPI()
              .subscribe(data => {
                this.parseData(data);
              });
           }
      
          parseData(jsonData: string) {
          //considering you get your data in json arrays
          for (let i = 0; i < jsonData[1].length; i++) {
               const data = new WikiData(jsonData[1][i], jsonData[2][i]);
               this.wikiData.push(data);
          }
        }
      }
      
    0 讨论(0)
提交回复
热议问题