简体   繁体   English

如何将HttpRequest中的值直接返回到变量中

[英]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如果您确实想这样做:使用 Promises

You can always transform your request to a Promise with the toPromise() function.您始终可以使用toPromise()函数将您的请求转换为 Promise。 BUT:但:

Angular is all Observable Angular 是所有 Observable

Angular has widely adapted Observables into its Components and therefore should be used with those as well. Angular 已将 Observable 广泛应用于其组件中,因此也应与这些组件一起使用。 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 Observable 不像你希望的那样工作

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 .httpClient返回的Observable (或任何与此相关的 Observable)不包含您想要获取的值,它表示一旦任何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.如果您不想像上面那样手动订阅,因为您担心内存泄漏和未关闭的订阅,您可以使用AsyncPipe angular 提供。 This pipe subscribes to a observable for you and transforms it into the most current value delivered.这个管道为你订阅一个 observable 并将其转换为最新的交付值。

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.即使我为您的问题建议了toPromise()方式,我也不是所有 async-await 东西的粉丝。 Observables combined with the rxjs Operators can make you a magician. Observables 结合 rxjs Operators 可以让你成为魔术师。 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.我建议像@Chund 推荐的那样存储可观察对象并使用异步管道订阅它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 调用函数并直接在 html 中更好地获取返回值或在变量中设置返回值并在 html 中更好地使用此变量? - Call a finction and get return value directly in html better or set return value in a variable and use this variable in html better? 如何从可观察的 http 请求中返回值并将其存储在局部变量中? - how to return value from observable http request and store it in local variable? 直接从 angular 模板更改变量值是一种好习惯吗 - Is it a good practice to change variable value directly from angular template 如何在Spring中直接从HandlerExceptionResolver返回错误响应 - How to return error response directly from HandlerExceptionResolver in spring Angular:如何直接从服务中操作组件中的@Input /局部变量? - Angular : How to Manipulate an @Input / local variable in component directly from a service? 在组件中保留 HttpRequest 值 - Keep HttpRequest value in the component 如何将函数的返回值分配给局部变量? - How to assign a return value of function to local variable? 如何将值返回给函数并通过变量访问它 - How to return value to function and access it via a variable 如何将Angular函数的返回值存储到变量中 - How to store in Angular fuction return value into variable 如何在 Angular 中声明一个带有返回方法的变量作为值? - How to declare a variable with a return method as value in Angular?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM