简体   繁体   中英

Assign a value to an internal variable in a function angular2

I have the following service in Angular2:

@Injectable()
export class MyService{

    private myServiceUrl= ....

    constructor(private http: Http) { }

    getService(): Promise<MyObject> {
        return this.http.get(this.myServiceUrl).map(response => response.json())
            .toPromise();
    }    
}

And I have this function in one of my components:

myFunction(): any{
    let toReturn: any;
    this.myService.getService().then(result => toReturn = result);
    console.log(toReturn);
    return toReturn;
  }

Basically, as you can see, I want to store in toReturn, the objects that it is returned by the promise of myService. I am looking to the rest call I have, and I am getting the proper json, but when I am trying to store it in the internal variable, I get undefinied in toReturn.

However, if I try this:

this.myService.getService().then(result=> console.log(result));

I am able to see the json I want.

I can do a function like this:

getService(address: string) {
        this.myService.getService().then(result=> this.result= result);
}

But I prefer to make my function to return an object. What am I doing wrong?

Remember that getService is asynchronous, so when your code reaches the line

return toReturn;

The toReturn variable has not yet received the data coming from the server.

The cleanest way to deal with this is to return the promise itself, so that the calling code will extract the data when it arrives from the server:

myFunction(): Promise<MyObject> 
{
    //return the promise that will output data in the future
    return this.myService.getService();
}

The calling code can access the data this way:

myFunction().then( result =>
    this.result= result
)

You can even remove a step by getting rid of myFunction because it's just a thin wrapper around getService() . Instead the calling code can simply do:

this.myService.getService().then(result => this.result = result)

And that's it.

Addendum to address your comments :

You must understand two concepts about asynchronous ops and promises:

  1. A promise is executed in a different thread , so the lines after the call to getService() are executed before the data arrives. That's why console.log() doesn't show you data at that point. That's also why trying to return the result there doesn't work

  2. the only place in code where you can capture the result of a promise is .then() . There you can do whatever you want with the result, including storing it in any variable. Just remember point 1 above, and don't expect to have access to the result on the very next line because then() occurs later in time on a different thread.

assign the json that comes from that service (which returns a promise), to an internal variable that I defined in the line above, it is not working. How can store it to an internal variable and return it

You cannot.

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