Get data outside of a service call

I'm using a service that gets data , that I will use it in my component.

ngOnInit() {
    this.EJnames= this.dataservice.getResults();
    this.generalinfosservice.getResults("nothing").then(data=>{this.datas=data; console.log(data)});
    console.log(this.datas);
  }

In my getResult() function I have a method that uses to Promise to get all data.

post( url, mockUrl, body) {
    if( environment.mocked ) {
        return this.httpClient.get( mockUrl ).toPromise().then( data => { return data} );
    } else {
        return this.httpClient.post( url, JSON.stringify( body ) )
            .toPromise()
            .then( data => {
                return data;
            }, ( err: any ) => {
                return this.handleError( err.message );
            } );
    }
}

The first console.log(data) is returning my data

but console.log(this.data) is returning an empty array.

How can I pass data to this.data or should I put my code in then "function" ?

2 answers

  • answered 2018-03-13 20:25 Daniel W Strimpel

    Anything that you need to do to process the data, etc. needs to go in the then function. The getResults method is asynchronous and the then method will be processed at some time later in the future when the promise resolves. When the code returns from the getResults method it will continue on executing the rest of the code in your ngOnInit method. It does not wait to execute the rest of your promise chain before moving onto the next line.

  • answered 2018-03-13 20:25 Tularis

    You've basically answered your own question. .then( data => { return data; })

    will return data to the event dispatcher. This will not set this.data = data;

    So the solution would be to change it to:

       .then( data => {
          this.data = data;
       })