JS / TS - 函数返回空数组

时间:2017-03-20 14:23:17

标签: javascript typescript

我有这个功能

populateGenerals() {

    var generals = [];
    this.productsService.getGenerals()
        .subscribe(data => {
            data.forEach(element => {
                generals.push({ id: element._id, text: element._id });
            });
            console.log(generals);
        });

    console.log(generals);
    return generals;
}
内部控制台给了我:

[{"id":"1","text":"red"},{"id":"2","text":"blue"}]

而外部控制台给了我:

[]

返回 generals 时,如何返回与内部控制台相同的数组?

更新/解决方案

populateGenerals() {
    this.loading = true;
    var generals = [];


    this.productsService.getGenerals()
        .subscribe(data => {
            this.loading = false;
            data.forEach(element => {
                generals.push({ id: element._id, text: element._id });
            });

            this.populateCallback(generals);
        });

    return this.generals;
}

populateCallback(array) {
    this.generals =  array;
}

0 个答案:

没有答案