In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-21 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly introduces the relevant knowledge of "what is the observable object, observer and RxJS operator in Angular". The editor shows you the operation process through an actual case. The operation method is simple, fast and practical. I hope this article "what is the observable object, observer and RxJS operator in Angular" can help you solve the problem.
Observable (observable object)
Observable (observable object) is an object in the RxJS library that can be used to handle asynchronous events, such as HTTP requests (in fact, in Angular, all HTTP requests return Observable). [recommended for related tutorials: "angular tutorial"]
Maybe you've come into contact with something called promise before, and they are essentially the same: both producers take the initiative to "push" products to consumers, while consumers passively receive them, but there is a big difference between them: Observable can send any number of values, and it won't be executed until it is subscribed! This is a feature that promise does not have.
Observable is used to transmit messages between the sender and the receiver, which you can think of as streams
When creating an Observable object, you need to pass in a function as an argument to the constructor. This function is called the subscriber function, which is where the producer pushes the message to the consumer.
The subscriber function is not executed until it is subscribe (subscribed) by the consumer until the subscribe () function is called, which returns a subscription object with a unsubscribe () function in which the consumer can refuse to receive the message at any time!
The subscribe () function takes an observer (observer) object as an input parameter
Messages can be sent synchronously or asynchronously
Observer (Observer)
With the observable object (sender), you need an observer (receiver) to observe the observable object. The observer implements the observer interface, which is an object that contains three attributes, all of which are functions, as follows:
The notification type indicates that next is necessary. It is executed under normal circumstances with the received value as the input parameter. It may be executed zero or more times. Error is optional. Execute in case of error. The error interrupts the execution of this observable object instance. Complete is optional. It is executed when the transmission is completed. Subscription
Only when someone subscribes to an instance of Observable will it start publishing values. When subscribing, you first call the subscribe () method of the observable object and pass it an observer object to receive notifications. As follows:
To demonstrate the principle of subscription, you need to create a new observable object. It has a constructor that can be used to create new instances, but for simplicity, you can also use some static methods defined on Observable to create some commonly used simple observable objects:
Of (... items): returns an instance of Observable that sends out the values provided in the parameters one by one synchronously.
From (iterable): converts its parameters to an Observable instance. This method is usually used to convert an array into an observable object (that sends multiple values).
Import {of} from "rxjs"; / / 1. Return an observable object through the of () method, and prepare to send three pieces of data to const observable = of (1mem2). / / 2. Implement the observer interface. Observer const observer = {next: (num: number) = > console.log (num), error: (err: Error) = > console.error ('Observer got an error:' + err), complete: () = > console.log ('Observer got a complete notification'),} / / 3, subscription. Call the subscribe () method subscription of the observable object, and the object passed in the subscribe () method is an observer observable.subscribe (observer).
The running results are as follows:
The above subscription can be written as follows: the parameter is not an object.
Observable.subscribe (num = > console.log (num), err = > console.error ('Observer got an error:' + err), () = > console.log ('Observer got a complete notification')); subscriber function
In the above example, the of () method is used to create observable objects, and this section uses constructors to create observable objects.
The Observable constructor can create any type of observable stream. When the subscribe () method of the observable object is executed, the constructor runs the parameters it receives as a subscription function. The subscription function takes an Observer object and publishes the value to the observer's next () method.
/ / 1. Custom subscriber function function sequenceSubscriber (observer: Observer) {observer.next (1); / / send data observer.next (2); / / send data observer.next (3); / / send data observer.complete (); return {unsubscribe () {}} } / / 2. Create a new observable object through the constructor, and the parameter is a subscriber function const sequence = new Observable (sequenceSubscriber); / / 3, subscribe to sequence.subscribe ({next (num) {console.log (num);}, / / accept data complete () {console.log ('Finished sequence');}})
The running results are as follows:
The above example demonstrates how to customize the subscription function, so now that we can customize the subscriber function, we can encapsulate the asynchronous code into the subscriber function of the observable object and send the data after the asynchronous code is executed. As follows:
Import {Observable} from 'rxjs'// Asynchronous function function fn (num) {return new Promise ((reslove, reject) = > {setTimeout () = > {num++ reslove (num)}, 1000)} / / create observable object Pass in the subscriber function const observable = new Observable ((x) = > {let num = 1 fn (num). Then (res = > x.next (res) / / Asynchronous Code execution completed, send data)}) / / subscribe to receive data, and you can call observable.subscribe (data = > console.log (data)) / / 2 Multicast instead.
Https://angular.cn/guide/observables#multicasting
RxJS operator
We can use a series of RxJS operators to process and transform these messages before they are received by the receiver, because these operators are pure functions.
Import {of} from 'rxjs';import {map} from' rxjs/operators';// 1, create an observable object and send data const nums = of (1,2,3); / / 2, create a function to accept the observable object const squareValues = map ((val: number) = > val * val); const squaredNums = squareValues (nums); squaredNums.subscribe (x = > console.log (x))
The above way I do not understand and difficult to accept, generally used in the following, using pipe to link multiple operators together
Import {map, Observable, filter} from 'rxjs'// creates observable objects Pass in the subscriber function const observable = new Observable ((x) = > {x.next (1) x.next (2) x.next (3) x.next (4)}). Pipe (map (value = > value*100), / / operator filter (value = > value = = 200) / / operator) .subscribe (data = > console.log (data)) / / 200 error handling
RxJS also provides the catchError operator, which allows you to handle known errors in the pipeline.
Suppose you have an observable object that initiates an API request and then maps the response returned by the server. If the server returns an error or the value does not exist, an error is generated. If you catch this error and provide a default value, the stream will continue to process these values without reporting an error. As follows:
Import {map, Observable, filter, catchError, of} from 'rxjs'const observable = new Observable ((x) = > {x.next (1) / / send data 1 and 2 x.next (2)}). Pipe (map (value = > {if (value = 1) {/ / 1, when the data sent is 1 Multiply it by 100return value*100} else {/ / 2, or throw an error throw new Error ('throw error') }}), / / 3, catch and handle the error here, send data 0 catchError ((err) = > {console.log (err) return of (0)}) .subscribe (data = > console.log (data), / / 4, because the error thrown above is handled by the catchError operator (resend the data) So here you can subscribe to the data without error err = > console.log ('cannot receive data:', err))
The final running result is as follows:
That's all for "what are observable objects, observers, and RxJS operators in Angular?" Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 298
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.