什么是.subscribe角? [英] what is .subscribe in angular?
问题描述
我正在通过英雄角度游应用程序,在路由过程中遇到了.subscribe方法.有人可以解释这里发生了什么吗?
I'm going through angular-tour-of-heroes app,and i encountered .subscribe method in routing.Can someone explain whats going on here?
应用程序链接- https://embed.plnkr.co/?show=preview
内部hero-detail.component.ts文件,
Inside hero-detail.component.ts file,
ngOnInit(): void {
this.route.paramMap
.switchMap((params: ParamMap) => this.heroService.getHero(+params.get('id')))
.subscribe(hero => this.hero = hero);
}
推荐答案
.subscribe
不是Angular2.
.subscribe
is not an Angular2 thing.
这是Angular内部使用的 rxjs
库的一种方法.
It's a method that comes from rxjs
library which Angular is using internally.
如果您在订阅新闻通讯时和订阅后都能想象自己,那么每次有新的新闻通讯时,他们都会将其发送到您的家中(调用subscribe中的方法).
If you can imagine yourself when subscribing to a newsletter and after subscribing, every time that there is a new newsletter, they will send it to your home (the method inside subscribe gets called).
订阅杂志来源(在rxjs
库中将其称为Observable
)时会发生这种情况
That's what happens when you subscribing to a source of magazines ( which they call it Observable
in rxjs
library)
所有Angular中的AJAX
调用都在后台使用此库,并且要使用其中的任何一个,您必须使用方法名称,例如get
,然后在其上调用subscribe,因为get
返回,然后Observable
.
All the AJAX
calls in Angular is using this library behind the scene and in order to use any of them, you've got to use the method name, e.g get
, and then call subscribe on it, because get
returns and Observable
.
另外,当您执行此操作时,<button (click)="doSomething()">
Angular在幕后使用Observables
并将您订阅该事物的源,在这种情况下,这是一个click
事件.
Also, when you're doing this <button (click)="doSomething()">
Angular is using Observables
behind the scene and subscribes you to that source of thing, which in this case is a click
event.
回到我们对Observables
和newsletter stores
的类比,只要您订阅了新杂志,只要有新杂志,他们就会将其发送给您,除非您继续阅读并unsubscribe
从他们那里,要实现这一点,您必须记住订阅号或ID,在rxjs
中它是这样的:
Back to our analogy of Observables
and newsletter stores
, after you've subscribed, as soon as and as long as there is a new magazine, they'll send it to you unless you go and unsubscribe
from them which for that to happen you've got to remember the subscription number or id, which in rxjs
it would be like :
let subscription = magazineStore.getMagazines().subscribe(
(newMagazine)=>{
console.log('newMagazine',newMagazine);
});
当您不想再获得杂志时:
And when you don't want to get the magazines anymore:
subscription.unsubscribe();
同样,
this.route.paramMap
返回一个Observable
,然后您正在订阅它.
which is returning an Observable
and then you're subscribing to it.
我的个人观点是rxjs
是JavaScript世界中最伟大的东西之一,在Angular中甚至更好.
My personal view is rxjs
was one of the greatest things that were brought to JavaScript world and it's even better in Angular.
有150种rxjs
方法(与lodash
方法非常相似),而您使用的方法称为switchMap
There are 150~ rxjs
methods ( very similar to lodash
methods) and the one that you're using is called switchMap
这篇关于什么是.subscribe角?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!