【问题标题】:Angular2 and typescript - how to add an array to a array from promise?Angular2和打字稿 - 如何将数组从promise添加到数组中?
【发布时间】:2016-06-12 01:23:34
【问题描述】:

在我的控制器中,我进行了一次休息调用来创建我的表格。我需要附加一些固定的行,我不知道该怎么做。

我想要这样的东西:

导出类环境{ id:字符串; 名称:字符串; }

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; });

【问题讨论】:

  • 承诺结果在哪里?您要添加的数组在哪里?
  • 来自订阅。环境 => this.environments = 环境
  • 这个问题与 TypeScript、Angular2 或 Promises 没有任何关系。因此,它真的应该被编辑成一个关于如何在 javascript 中组合两个数组的简单问题。

标签: typescript angular


【解决方案1】:

你正在寻找Array.concat():

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

【讨论】:

    猜你喜欢
    • 2018-08-18
    • 1970-01-01
    • 2022-01-24
    • 2017-11-18
    • 2016-10-15
    • 2019-05-27
    • 2022-01-16
    • 1970-01-01
    • 2018-06-10
    相关资源
    最近更新 更多