【问题标题】:Merge objects in Angular 2 [duplicate]在Angular 2中合并对象[重复]
【发布时间】:2017-06-05 06:18:59
【问题描述】:

我无法合并 3 个对象数组。我的目标是将 3 个数组合并为一个并将 HTTP POST 发送到服务器。

我曾尝试使用 concat,但出现此错误:

例外:./PreviewEmailPage 类 PreviewEmailPage_Host 中的错误 - 内联模板:0:0 原因:无法读取未定义的属性“concat”

这些是我的代码:

import { Component } from '@angular/core';
import { NavParams, NavController, LoadingController } from 'ionic-angular';
import { Validators, FormGroup, FormControl } from '@angular/forms';

import { Http, Headers} from '@angular/http';
import 'rxjs/add/operator/map';
import { Storage } from '@ionic/storage';


@Component({
  selector: 'preview-email-page',
  templateUrl: 'preview-email.html',
})
export class PreviewEmailPage {
  headers: Headers;
  loading: any;
  url: string;
  preview: any[];

  FirstArray: any[];
  SecondArray: any[];
  ThirdArray: any[];
  PostData: any[];

  constructor(
    public nav: NavController,
    public navParams: NavParams,
    public loadingCtrl: LoadingController,
    public localStorage: Storage,
    public http: Http,
  ) {
    this.localStorage.get('FirstArray').then((value) => {
      this.FirstArray= value;
    })
    this.localStorage.get('SecondArray').then((value) => {
      this.SecondArray= value;
    })
    this.localStorage.get('ThirdArray').then((value) => {
      this.ThirdArray= value;
    })

    this.PostData = this.FirstArray.concat(this.SecondArray);
    this.PostData = this.PostData.concat(this.ThirdArray);

    this.loading = this.loadingCtrl.create();
  }

  ionViewWillEnter(){
    this.headers = new Headers();
    this.headers.append("Content-Type", "application/x-www-form-urlencoded");
    console.log(this.PostData);
    this.getPreview();
  }

  getPreview(){
    this.loading.present();
    this.url = 'https://domain.com/REST/getpreview.php';
    this.http.post(this.url, this.PostData, {headers: this.headers}).map(res => res.json()).subscribe(res => {
      console.log(res);
      this.preview = res;
    }, err => {
      console.log('error');
    })
  }

}

【问题讨论】:

  • 正如.get(...).then(...) 所建议的,您从本地存储中获取数据是异步进行的。因此,当您进行串联时,这些字段尚未设置。

标签: javascript arrays angular typescript ionic2


【解决方案1】:

由于this.localStorage.get 是一个异步操作,所以在执行then 之前,您的this.FirstArray 不会被定义。

您可以做的是与Promise.all 并行运行它们:

Promise.all([this.localStorage.get('FirstArray'), this.localStorage.get('SecondArray'), this.localStorage.get('ThirdArray')]).then(values => { 
  this.FirstArray= values[0];
  this.SecondArray= values[1];
  this.ThirdArray= values[2];
  this.PostData = this.FirstArray.concat(this.SecondArray);
  this.PostData = this.PostData.concat(this.ThirdArray);
});

【讨论】:

  • 感谢您的回答,但现在出现此错误:异常:未捕获(承诺中):TypeError:无法读取未定义的属性“concat”
  • @RedzwanLatif 您的回调是否返回所需的值? console.log 在回调中记录它们以查看它们返回的内容。
猜你喜欢
  • 2016-07-22
  • 2017-07-26
  • 2019-12-20
  • 2018-01-04
  • 2013-12-26
  • 2020-05-20
  • 1970-01-01
  • 1970-01-01
  • 2016-10-03
相关资源
最近更新 更多