如何在Angular中将JavaScript数组推送到数组中

时间:2017-05-25 20:55:17

标签: javascript angular

Angular组件从JavaScript文件接收一个数组,该文件解析JSON并将其返回到数组中。但是,我遇到的问题是模板中的组件无法识别变量jsonArray:any,它表示未定义。

import {Component, NgModule} from '@angular/core'
import {BrowserModule} from '@angular/platform-browser'
import '../assets/js/jsonReader.js'

declare var myExtObject: any;
declare var webGlObject: any;

@Component({
  selector: 'app-root',
 template: `
     <div>
        {{jsonArray.name}}
    </div>
  `,
})
export class AppComponent {

 test: Object[];
 jsonArray:any;
 output = [];

  constructor() {
    this.jsonArray = webGlObject.init();
  }

}

这是JavaScript代码

var webGlObject = (function () {
  return {
    init: function () {
      getJsonArryObject();
    }
  }
})(webGlObject || {})

function getJsonArryObject() {
  loadJSON(function (response) {
    // Parse JSON string into object
    var js = JSON.parse(response);
  });

  //return getObjects(js, key, val);
}

这是JSON文件

[
  {
    "name": "ar",
    "hasTributaryInfo": true,
    "hasTributaryInfoMandatory": false,
    "isRazonSocialMandatory": true,
    "isRUCMandatory": false,
    "array": [
      1,
      2,
      3
    ]
  },
  {
    "name": "sa",
    "hasTributaryInfoMandatory": true,
    "hasTributaryInfo": true,
    "isRazonSocialMandatory": true,
    "isRUCMandatory": true,
    "object": {
      "a": "b",
      "c": "d",
      "e": "f"
    }
  },
  {
    "name": "co",
    "hasTributaryInfoMandatory": false,
    "hasTributaryInfo": false,
    "isRazonSocialMandatory": false,
    "isRUCMandatory": false
  }
]

1 个答案:

答案 0 :(得分:0)

解决方案1 ​​:您可以使用Observables:

var webGlObject = (function () {
  return {
    init: function () {
      return getJsonArryObject();
    }
  }
})(webGlObject || {})

function getJsonArryObject() {
  let subject = new Subject();

  loadJSON(function (response) {
    // Parse JSON string into object
    var js = JSON.parse(response);
    subject.next(js);
    subject.complete();
  });

  return subject;
}

然后你可以:

@Component({
  selector: 'app-root',
 template: `
     <div *ngFor="let item in jsonArray$ | async">
        {{ item.name }}
    </div>
  `,
})
export class AppComponent {

 jsonArray$: Observable<any>;

  constructor() {
    this.jsonArray$ = webGlObject.init();
  }
}

解决方案2 :您可以使用Promises:

var webGlObject = (function () {
  return {
    init: function () {
      return getJsonArryObject();
    }
  }
})(webGlObject || {})

function getJsonArryObject() {
  return new Promise((resolve, reject) => {

    loadJSON(function (response) {
      // Parse JSON string into object
      var js = JSON.parse(response);
      resolve(js);
    });
  });
}

然后你可以:

@Component({
  selector: 'app-root',
 template: `
     <div *ngFor="let item in jsonArray">
        {{ item.name }}
    </div>
  `,
})
export class AppComponent {

 jsonArray: any[] = [];

  constructor() {
    webGlObject.init().then(data => this.jsonArray = data);
  }
}