简体   繁体   中英

How to return value from HttpRequest directly into a variable

I have a request :

// api-service.ts
getUsers() {
    return this.http.get(this.BaseUrl + 'users/', httpOptions);
}

I want to set up the result into a variable like this :

// users-component.ts
ngOnInit() { 
    this.users = this.api.getUsers();
}

Currently i have to do something like this :

// users-component.ts
ngOnInit() { 
    this.api.getUsers().subscribe(res => {
        this.users = res;
    })
}

i Try something like that :

// api-service.ts
getUsers() {
    return this.http.get(this.BaseUrl + 'users/', httpOptions).pipe(
     map (res => { return res; })
    );
}

But it does not work.

I juste want to set up the result of this request into a variable without use the subscribe where my variable is.

Thanks

Actually you propably do NOT want to do so, but let me work this through.

If you definetly want to do so: use Promises

You can always transform your request to a Promise with the toPromise() function. BUT:

Angular is all Observable

Angular has widely adapted Observables into its Components and therefore should be used with those as well. You buy into a lot of advantages by doing so. For example you do not need to wait for your client to retrieve the data requested and can instead do other things.

Observables do not work like you want them to do

The Observable returned from the httpClient (or any Observable for that matter) does not contain the value you want to get it represents the pipeline through which a stream of data can published once any subscription .

Meaning that this stream will not output any data unless subscribed to.

If you do not want to manually subscribe to like you did above, because you are concerned about memory leaks and unclosed subscriptions, you could go with the AsyncPipe angular provides. This pipe subscribes to a observable for you and transforms it into the most current value delivered.

You could do:

// users-component.ts
async ngOnInit() { 
    this.user = await this.api.getUsers().toPromise();
}

Edit:

Even if I suggested the toPromise() way for your question I am not a fan ob all the async-await stuff. Observables combined with the rxjs Operators can make you a magician. The learning curve is high, but it is really rewarding. I recommend to store the observable and subscribe to it with the async pipe just as @Chund recommended.

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