在Angular 2打字稿中进行服务调用后,无法使用数组持有者连接数组

时间:2016-04-22 13:30:08

标签: typescript angular

我在加载时将数据数组加载到数组变量(范围)中,如

    ngOnInit(){
    this.error = "";
    this.countries=[];
    this._countryService.getCountriesByRegion()
     .subscribe(
        data => this.countries = data,
        error => this.error = "keyword " + this.region + " is invalid."
     );

然后onscrolling我将另一个数组与前一个数组连接起来,如

        onScroll () {
        this._countryService.getCountriesfortesting()
        .subscribe(
        data => this.countries.concat(data),
        error => this.error = "keyword " + this.region + " is invalid."
     );

}

但是在进入getCountriesfortesting()的成功函数时,this.countries没有任何内容。所以我无法将前一个数组与最新数组合并。 希望你能理解。感谢adv :)借口错误,如果有的话。

1 个答案:

答案 0 :(得分:2)

你可以试试这个:

onScroll () {
    this._countryService.getCountriesfortesting()
    .subscribe(
    data => {
      this.countries = this.countries.concat(data);
    },
    error => this.error = "keyword " + this.region + " is invalid."
 );

concat方法不更新源数组并返回连接的数组。

请参阅此页:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/concat