What is observable, observer and subscribe in angular?

天涯浪子 提交于 2020-05-22 21:14:47

问题


I am learning angular and i got confuse in these observable, observer and subscribe thing. So please explain.


回答1:


Here is a simple visual to see the difference:

As seen above ... an Observable is a stream of events or data. They are often returned from Angular methods, such as the http.get and the myinputBox.valueChanges.

Subscribing "kicks off" the observable stream. Without a subscribe (or an async pipe) the stream won't start emitting values. It's similar to subscribing to a newspaper or magazine ... you won't start getting them until you subscribe.

The subscribe method takes in an observer. An observer has three methods:

  • The method to process each time an item is emitted from the observable.

  • The method to process any error that occurs.

  • The method to clean up anything when the observer completes. This last one is seldom used when working with Angular's observables.

Hope this helps.

(And I agree ... trying to see the forest through the trees of the docs is quite a challenge. I understand they are working to improve them.)




回答2:


Here is some key points :

1) Definition: "Observable and Observer" is a pattern of message passing from publisher to subscriber.
2) Flow of functionality:

  • Observable is created

  • Observer subscribe to Observable

  • Observable can pass message to observer
  • each time, when the observable passes a not a message it is received by Observer

3) Real-time usage of Observable and Observer

  • While receiving response from AJAX
  • While performing large tasks in client(browser)


来源:https://stackoverflow.com/questions/51520584/what-is-observable-observer-and-subscribe-in-angular

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!