在Angular4中,订阅中的数据为null

在Angular4中,订阅中的数据为null,angular,typescript,Angular,Typescript,我用我的SUBSCRIBE获取数据,我显示这些数据,然后我调用我的函数,但我的函数显示“null”。对不起我的英语。谢谢 this.service.prepareNewVersion().subscribe(data2 => { console.log("data2 ", data2); this.service.myBlockPeriod = data2; console.log(" prepareNewVersion ", this.se

我用我的SUBSCRIBE获取数据,我显示这些数据,然后我调用我的函数,但我的函数显示“null”。对不起我的英语。谢谢

 this.service.prepareNewVersion().subscribe(data2 => {
       console.log("data2 ", data2);
       this.service.myBlockPeriod = data2;
       console.log(" prepareNewVersion ",   this.service.myBlockPeriod);
  });
 console.log(" before ",   this.service.myBlockPeriod);
 this.showYearsExec();


private showYearsExec() {
        console.log("showYearsExec", this.service.myBlockPeriod);
        let list: Array<string> = this.service.myBlockPeriod;

    if (list !== null) {

        list.forEach(element => {
            this.arrayYears.push(element.substring(0, 4));
        });



        // Se eliminan los años repetidos.
        let unique = this.arrayYears.filter(function (elem, index, self) {
            return index === self.indexOf(elem);
        })

        // Combo de años de la vista.
        this.arrayYears = unique;

        // Se añaden al servicio
        this.service.yearsInExec = unique;
    }

}
this.service.prepareNewVersion().subscribe(数据2=>{
console.log(“data2”,data2);
this.service.myBlockPeriod=data2;
log(“prepareNewVersion”,this.service.myBlockPeriod);
});
console.log(“before”,this.service.myBlockPeriod);
这是showYearsExec();
私人showYearsExec(){
log(“showYearsExec”,this.service.myBlockPeriod);
let list:Array=this.service.myBlockPeriod;
如果(列表!==null){
list.forEach(元素=>{
this.arrayYears.push(element.substring(0,4));
});
//这是埃利米南·洛斯阿尼奥斯·雷普蒂多斯。
let unique=this.arrayYears.filter(函数(elem、index、self){
返回索引===self.indexOf(elem);
})
//拉维斯塔酒店。
this.arrayYears=唯一;
//塞阿尼亚丁服务酒店
this.service.yearsInExec=唯一;
}
}

您的代码是异步执行的,在执行“this.showYearsExec()”时,“prepareNewVersion()”方法的承诺尚未解决,因此结果为空

在订阅方法中执行“this.showYearsExec();”,如下所示:

this.service.prepareNewVersion().subscribe(data2 => {
       console.log("data2 ", data2);
       this.service.myBlockPeriod = data2;
       console.log(" prepareNewVersion ",   this.service.myBlockPeriod);
       console.log(" before ",   this.service.myBlockPeriod);
       this.showYearsExec();
  });

代码是异步执行的,在执行“this.showYearsExec()”时,“prepareNewVersion()”方法的承诺尚未解析,因此结果为空

在订阅方法中执行“this.showYearsExec();”,如下所示:

this.service.prepareNewVersion().subscribe(data2 => {
       console.log("data2 ", data2);
       this.service.myBlockPeriod = data2;
       console.log(" prepareNewVersion ",   this.service.myBlockPeriod);
       console.log(" before ",   this.service.myBlockPeriod);
       this.showYearsExec();
  });