简体   繁体   中英

I get null with datas in a subscribe in Angular4

I get the data with my susbscribe, I show this datas, then I call my function but my function says "null". Sorry for my english. Thanks.

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

}

在此处输入图片说明

Your code is executed asynchronously, by the time "this.showYearsExec ()" is executed the promise of the "prepareNewVersion ()" method is not yet resolved, so the result is null.

do " this.showYearsExec();" in your subscribe method like this :

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM