如何在不使用订阅的情况下从 observable 中获取值 [英] How can i get values from observable without using subscribe

查看:89
本文介绍了如何在不使用订阅的情况下从 observable 中获取值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我开始学习 angular 时,我读了一些博客,说使用异步管道更好,因为它可以自动取消订阅数据流.所以我愿意

HTML

<ul><li *ngFor="让用户的用户 |async">{{ user.name }}</li>

TS 文件

导出类 AppComponent 实现 OnInit {构造函数(私有 http:HttpClient){};用户:任何;ngOnInit() {this.users = this.http.get('https://jsonplaceholder.typicode.com/userss');控制台日志(this.users);}}

所以在 ngOnInit 方法中控制台日志

console.log(this.users);

给我

Observable {_isScalar: false, source: Observable, operator: MapOperator

我使用异步管道获取了 HTML 中的值,但是如果我需要根据我从后端获得的用户在我的组件网络中执行一些逻辑 - ts 文件怎么办.

如果我想要里面的数据,我可以通过订阅来完成.但我不希望那样,因为一开始我从异步管道开始,因为我不想手动取消订阅.

那么在这种情况下,我怎样才能在没有订阅的情况下从 observable 中获取值呢?组件已销毁,我不应该关心取消订阅.

解决方案

您使用异步管道的方法完全没问题.但是它会为你做的是订阅可观察的,因为你得到了数据.它也会处理取消订阅,因为使用异步管道非常方便.

这就是 observables 的本质:只有订阅它才能获得值.

如果你想在你的组件中拥有这些值,你需要订阅.

When i started learning angular i readed blogs that using async pipe is better because it makes automatically unsubscribe from the data stream. So i do

HTML

<div *ngIf="users | async">
    <ul>
        <li *ngFor="let user of users | async">{{ user.name }}</li>
    </ul>
</div>

TS FILE

export class AppComponent implements OnInit {
  constructor(private http: HttpClient) {};
  users: any;
  ngOnInit() {
   this.users = this.http.get('https://jsonplaceholder.typicode.com/userss');
   console.log(this.users);
  }
}

so in the ngOnInit method the console log

console.log(this.users);

gives me

Observable {_isScalar: false, source: Observable, operator: MapOperator

I got the values in HTML with the async pipe, but what if i will need to do some logic in my componenet - ts file based on the users that i got from backend.

If i want the data inside i could do it with subscribe. But i don't want that because at first place i started with async pipe because i don't want to manualy unsubscribe from it.

So in this situation how can i get the value from the observable without subscribe so at the end when the component is detroyed i should not care about unsubscribing.

解决方案

Your approach with the async pipe is totally fine. But what it will do for you is subscribing to the observable, because of that you get the data. It will also handle to unsubscribe, because of that using the async pipe is very convenient.

And this is the nature of observables: you only get values if you subscribe to it.

If you want to have the values in your component you need to subscribe.

这篇关于如何在不使用订阅的情况下从 observable 中获取值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆