[英]Angular - what is the best approach in retrieving data
I've been facing a few alternatives in retrieving data from a simple API call when you will always get a single response, and I want to know what would be the best approach.在从简单的 API 调用中检索数据时,我一直面临着几种选择,当您总是会得到一个响应时,我想知道什么是最好的方法。
Initially I've used the plain subscribe
, then I've learnt about memory leaks.最初我使用普通的
subscribe
,然后我了解了 memory 泄漏。 Later I've used either _service.pipe(take(1)).subscribe
or packages like untilDestroyed
that cancel the subscription upon component destruction.后来我使用了
_service.pipe(take(1)).subscribe
或像untilDestroyed
这样的包,它们在组件销毁时取消订阅。
Assigning the subscription to a variable and unsubscribing on ngOnDestroy
is the least desirable option for me.将订阅分配给变量并取消订阅
ngOnDestroy
对我来说是最不理想的选择。
Another option is converting the observable to a promise and then use a bit of syntactic sugar with async/await
.另一种选择是将 observable 转换为 promise ,然后在
async/await
中使用一些语法糖。
Since I am periodically refactoring my code, the question remains.由于我定期重构我的代码,所以问题仍然存在。 What is the best approach and why?
什么是最好的方法,为什么?
Using subscribe
with http requests
is totally fine and you should't worry so much about memory leaks because the stream completes right after the data from the server is passed trough it.将
subscribe
与http requests
一起使用完全没问题,您不必太担心 memory 泄漏,因为 stream 在服务器传递数据后立即完成。
You should worry about the subscriptions on long-lived observables/subjects which don't complete automatically after the first value.您应该担心在第一个值之后不会自动完成的长期可观察对象/主题的订阅。 In that case you can use operators or the subscription object in order to manage those subscriptions.
在这种情况下,您可以使用运算符或订阅 object 来管理这些订阅。 Some useful operators are
take()
, first()
, takeUntil()
, takeWhile()
一些有用的运算符是
take()
, first()
, takeUntil()
, takeWhile()
One approach that I like is to create an observable on my component and I often call it isAlive$
and inside the ngOnDestroy
I emit a value from from this subject in order to cancel all my subscriptions.我喜欢的一种方法是在我的组件上创建一个 observable,我经常将其称为
isAlive$
,在ngOnDestroy
,我从这个主题中发出一个值,以取消我的所有订阅。
class Cmp {
isAlive$ = new Subject();
ngOnInit() {
this.someLongLivedObservable$.pipe(takeUntil(this.isAlive$)).subscribe(() => {
// do something
});
}
ngOnDestroy() {
this.isAlive$.next();
this.isAlive$.complete();
}
}
Also you can connect subscriptions like:您还可以连接订阅,例如:
const subscription1 = observable1.subscribe(val => console.log(val));
const subscription2 = observable2.subscribe(val => console.log(val));
subscription1.add(subscription2);
When we join subscriptions we can unsubscribe to all the subscriptions that were joined by calling unsubscribe on the first.当我们加入订阅时,我们可以取消订阅所有加入的订阅,方法是先调用 unsubscribe。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.