2017-01-20 45 views
-1

Im在合并3个对象数组时遇到问题。我的目标是将3个数组合并到一个并将HTTP POST发送到服务器。在Angular 2中合并对象

我一直在使用的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'); 
    }) 
    } 

} 
+0

正如'获得(......)建议,然后(...)'从本地存储你的抓取正在发生的事情*。 * **异步。因此,当你进入串联时,这些字段尚未设置。 – jonrsharpe

回答

1

由于this.localStorage.get是指在执行异步操作的this.FirstArray没有,直到该then定义。

你能做的就是跑什么他们都在平行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); 
}); 
+0

感谢您的答案,但现在有这个错误:EXCEPTION:Uncaught(承诺):TypeError:无法读取未定义的属性'concat' –

+0

@RedzwanLatif您的回调是否返回所需的值? console.log里面的回调,看看他们回报。 – echonax