angular - Show asynchronous datas of subscribe -


this question has answer here:

i use loop retrieve data stored in firebase subscribe function , foreach. when console.log of datas in subscribe ("=== subscribe ===") have result, when console.log outside ("=== home ===" , "=== return ==="), have result :

screen of console.log

i suppose comes fact asynchronous, how fix problem please ?

this code :

statut: firebaselistobservable<any[]>;   statuts: array<any> = [];    // données à enregistrer dans firebase   dateoftheday: string;   dayofweek: number;    constructor(public afdb: angularfiredatabase, public storage: storage) {     moment.locale('fr');     this.dateoftheday = moment().format('l'); // date au format : 04/07/2017     this.dayofweek = moment().day(); // numéro du jour de la semaine (ex : 1 pour lundi)     this.statut = this.afdb.list('/statut');   }    statustoshow() {     this.statut.subscribe(statut => {       statut.foreach(s => {         if (this.dateoftheday === s.statut_date_tache) {           if (s.statut_id_tache in this.statuts === false) {             this.statuts[s.statut_id_tache] = s;           }         }       });        console.log('=== subscribe ===');       console.log(this.statuts);     });      console.log('=== return ===');     console.log(this.statuts);      return this.statuts;   } 

thanks in advance

comment: borderline exact duplicate, latter part of question not, therefore answer.

you correct assumption asynchronous, , presented here how return response observable/http/async call in angular2? need handle inside callback (subscribe). but, here want return response. cannot that, said here: https://stackoverflow.com/a/39296015 not possible subscribe.

what can do, presented in answer, can use map , return observable, can subscribe or use async pipe if want use in view.

call statustoshow() in service component need , subscribe value:

service:

statustoshow() {   return this.afdb.list('/statut').map(statut => {     for(let s of statut) {       if (this.dateoftheday === s.statut_date_tache) {         if (s.statut_id_tache in this.statuts === false) {           return localstatuts[s.statut_id_tache] = s;         }       }     }     // return else if value not found above   }); } 

then can subscribe observable in component , statut value:

component:

constructor(private service: todolistservice) { }  ngoninit() {   this.service.statustoshow()     .subscribe(statut => this.statut = statut) } 

i suggest check official http-tutorial. know using firebase, idea same :)


Comments

Popular posts from this blog

networking - Vagrant-provisioned VirtualBox VM is not reachable from Ubuntu host -

c# - ASP.NET Core - There is already an object named 'AspNetRoles' in the database -

ruby on rails - ArgumentError: Missing host to link to! Please provide the :host parameter, set default_url_options[:host], or set :only_path to true -