Angular2和typescript - 如何从promise中添加数组到数组?

时间:2016-06-11 08:33:49

标签: typescript angular

在我的控制器中,我打个电话来创建我的桌子。我需要附加一些固定的行,我不知道该怎么做。

我想要这样的事情:

export class Environment {     id:string;     name:string; }

environments: any[]; 
production = new Environment('1', 'production');
development = new Environment('2', 'development');

    ngOnInit(){
            this.environmentService.getEnvironments()
                .subscribe(environments => this.environments = environments,null,() => { this.isLoading = false; });

        } 

那么如何将数组添加到promise结果中?“

  [this.production,this.development] + this.environments;

拟议解决方案的结果:

 staging: Environment = {
        id: '111',
        name: 'staging'
};

environments = [this.staging];

[ { "id": "111", "name": "staging" }, [ { "id": "86aa96e8-0383-4bce-b833-be3c21f47306", "name": "cloud" } ] ]

云的名称来自服务器。如此接近,但应该是这样的:

[ { "id": "111", "name": "staging" },{ "id": "86aa96e8-0383-4bce-b833-be3c21f47306", "name": "cloud" } ]

这有效但有更好的方法吗?:

this.environmentService.getEnvironments()
            .subscribe(environments => {
                for (var i = 0; environments.length > i; i++) 
                { this.environments.push(environments[i])}

            },null,() => { this.isLoading = false; });

1 个答案:

答案 0 :(得分:1)

您正在寻找Array.concat()

this.environmentService.getEnvironments()
  .subscribe(env => { this.environments = this.environments.concat(env); },
    null,
    () => { this.isLoading = false; }
  );