search
HomeWeb Front-endJS TutorialA brief analysis of observable objects, observers and RxJS operators in Angular

This article will introduce you to the observable objects (Observable), observers (observer) and RxJS operators in Angular. I hope it will be helpful to everyone!

A brief analysis of observable objects, observers and RxJS operators in Angular

Observable (observable object)

Observable (observable object) is inside the RxJS library An object that can be used to handle asynchronous events, such as HTTP requests (in fact, in Angular, all HTTP requests return Observable). [Recommended tutorials: "angular tutorial"]

Perhaps, you have come into contact with something called promise before. They are essentially the same: they are all produced The operator actively "push" products to consumers, while consumers passively receive them, but there is still a big difference between them: Observable can send any number of values, and, after being subscribed Before, it would not execute ! This is a feature that promise does not have.

  • Observable is used to transmit messages between the sender and the receiver. You can regard these messages as streams
  • When creating Observable object, you need to pass in a function as a parameter of the constructor. This function is called Subscriber function . This function is where the producer pushes messages to the consumer.
  • Before being subscribe (subscribed) by the consumer, the subscriber function will not be executed until the subscribe() function is called, which returns a subscription object, There is a unsubscribe() function inside, and consumers can refuse to receive messages at any time!
  • subscribe()The function receives an observer(observer) object as an input parameter
  • The sending of the message can be synchronous or Asynchronous

observer (observer)

With an observable object (sender) , you need an observer (receiver) To observe observable objects, the observer must implement the observer interface, which is an object containing three properties, all of which are functions, as follows:

##nextRequired. Use the received value as input parameter and execute under normal circumstances. May be executed zero or more times. errorOptional. Executed in case of error. Errors interrupt the execution of this observable object instance. completeOptional. Executed when the transfer is completed.

Subscription

Only when someone subscribes to an instance of Observable will it start publishing values. When subscribing, you must first call the subscribe() method of the observable object and pass it an observer object to receive notifications. As follows:

In order to demonstrate the principle of subscription, a new observable object needs to be created first. It has a constructor that can be used to create new instances, but to be more concise, you can also use some static methods defined on Observable to create some commonly used simple observable objects:

  • of(...items): Returns an Observable instance, which sends the values ​​ provided in the parameters one by one in a synchronous manner.
  • from(iterable) : Converts its argument to an Observable instance. This method is usually used to convert an array into an observable object (which sends multiple values).
import { of } from "rxjs";
// 1、通过 of() 方法返回一个可观察对象,并准备将1,2,3三个数据发送出去
const observable = of(1, 2, 3);	
// 2、实现 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、订阅。调用可观察对象的 subscribe() 方法订阅,subscribe() 方法中传入的对象就是一个观察者
observable.subscribe(observer);

The running results are as follows:


# The above subscription can be directly changed to the following: 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 an observable object. This section uses the constructor to create an observable object.

Observable The constructor can create any type of observable stream. When the subscribe() method of the observable object is executed, this constructor will run the parameters it receives as the subscription function. The subscription function will receive an Observer object and publish the value to the next() method of the observer.

// 1、自定义订阅者函数
function sequenceSubscriber(observer: Observer<number>) {
  observer.next(1);	// 发送数据
  observer.next(2);	// 发送数据
  observer.next(3);	// 发送数据
  observer.complete();
  return {unsubscribe() {}};
}

// 2、通过构造函数创建一个新的可观察对象,参数就是一个订阅者函数
const sequence = new Observable(sequenceSubscriber);

// 3、订阅
sequence.subscribe({
  next(num) { console.log(num); },	// 接受数据
  complete() { console.log(&#39;Finished sequence&#39;); }
});

The running results are as follows:

A brief analysis of observable objects, observers and RxJS operators in Angular

The above example demonstrates how to customize the subscription function, so since you can customize the subscriber function, we can encapsulate the asynchronous code into the subscriber function of the observable object, and then send the data after the asynchronous code is executed. As follows:

import { Observable } from &#39;rxjs&#39;
// 异步函数
function fn(num) {
    return new Promise((reslove, reject) => {
        setTimeout(() => {
            num++
            reslove(num)
        }, 1000)
    })
}
// 创建可观察对象,并传入订阅者函数
const observable = new Observable((x) => {
    let num = 1
    fn(num).then(
    	res => x.next(res)	// 异步代码执行完成,发送数据
    ) 
})
// 订阅,接收数据,可以改为链式调用
observable.subscribe(data => console.log(data))	// 2

Multicast

https://angular.cn/guide/observables#multicasting

RxJS Operator

We can use a series of RxJS operators to perform a series of processing and conversion on these messages before they are received by the receiver, because these operators are all pure functions.

import { of } from &#39;rxjs&#39;;
import { map } from &#39;rxjs/operators&#39;;
// 1、创建可观察对象,并发送数据
const nums = of(1, 2, 3);
// 2、创建函数以接受可观察对象
const squareValues = map((val: number) => val * val);
const squaredNums = squareValues(nums);

squaredNums.subscribe(x => console.log(x));

I don’t understand the above method and it is difficult to accept it. Generally, the following method is commonly used. Use pipe to link multiple operators.

import { map, Observable, filter } from &#39;rxjs&#39;

// 创建可观察对象,并传入订阅者函数
const observable = new Observable((x) => {
    x.next(1)
    x.next(2)
    x.next(3)
    x.next(4)
}).pipe(
    map(value => value*100),		// 操作符
    filter(value => value == 200)	// 操作符
)
.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 that makes API requests and then maps the responses 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 processing those values ​​without reporting an error. As follows:

import { map, Observable, filter, catchError, of } from &#39;rxjs&#39;

const observable = new Observable((x) => {
        x.next(1)	// 发送数据 1 和 2
        x.next(2)
}).pipe(
    map(value => {
        if (value === 1) {	// 1、当发送的数据为 1 时,将其乘以 100
            return value*100
        } else {	// 2、否则抛出错误
            throw new Error(&#39;抛出错误&#39;);
        }
    }),
    // 3、此处捕获错误并处理错误,对外发送数据 0
    catchError((err) => {
        console.log(err)
        return of(0)
    })
)
.subscribe(
    data => console.log(data),
    // 4、由于上面抛出的错误被 catchError 操作符处理(重新发送数据)了,所以这里能顺利订阅到数据而不报错
    err => console.log(&#39;接受不到数据:&#39;, err)
)

The final running result is as follows:

A brief analysis of observable objects, observers and RxJS operators in Angular

For more programming-related knowledge, please visit: Programming Video! !

Notification Type Description

The above is the detailed content of A brief analysis of observable objects, observers and RxJS operators in Angular. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:csdn. If there is any infringement, please contact admin@php.cn delete
Is JavaScript Written in C? Examining the EvidenceIs JavaScript Written in C? Examining the EvidenceApr 25, 2025 am 12:15 AM

Yes, the engine core of JavaScript is written in C. 1) The C language provides efficient performance and underlying control, which is suitable for the development of JavaScript engine. 2) Taking the V8 engine as an example, its core is written in C, combining the efficiency and object-oriented characteristics of C. 3) The working principle of the JavaScript engine includes parsing, compiling and execution, and the C language plays a key role in these processes.

JavaScript's Role: Making the Web Interactive and DynamicJavaScript's Role: Making the Web Interactive and DynamicApr 24, 2025 am 12:12 AM

JavaScript is at the heart of modern websites because it enhances the interactivity and dynamicity of web pages. 1) It allows to change content without refreshing the page, 2) manipulate web pages through DOMAPI, 3) support complex interactive effects such as animation and drag-and-drop, 4) optimize performance and best practices to improve user experience.

C   and JavaScript: The Connection ExplainedC and JavaScript: The Connection ExplainedApr 23, 2025 am 12:07 AM

C and JavaScript achieve interoperability through WebAssembly. 1) C code is compiled into WebAssembly module and introduced into JavaScript environment to enhance computing power. 2) In game development, C handles physics engines and graphics rendering, and JavaScript is responsible for game logic and user interface.

From Websites to Apps: The Diverse Applications of JavaScriptFrom Websites to Apps: The Diverse Applications of JavaScriptApr 22, 2025 am 12:02 AM

JavaScript is widely used in websites, mobile applications, desktop applications and server-side programming. 1) In website development, JavaScript operates DOM together with HTML and CSS to achieve dynamic effects and supports frameworks such as jQuery and React. 2) Through ReactNative and Ionic, JavaScript is used to develop cross-platform mobile applications. 3) The Electron framework enables JavaScript to build desktop applications. 4) Node.js allows JavaScript to run on the server side and supports high concurrent requests.

Python vs. JavaScript: Use Cases and Applications ComparedPython vs. JavaScript: Use Cases and Applications ComparedApr 21, 2025 am 12:01 AM

Python is more suitable for data science and automation, while JavaScript is more suitable for front-end and full-stack development. 1. Python performs well in data science and machine learning, using libraries such as NumPy and Pandas for data processing and modeling. 2. Python is concise and efficient in automation and scripting. 3. JavaScript is indispensable in front-end development and is used to build dynamic web pages and single-page applications. 4. JavaScript plays a role in back-end development through Node.js and supports full-stack development.

The Role of C/C   in JavaScript Interpreters and CompilersThe Role of C/C in JavaScript Interpreters and CompilersApr 20, 2025 am 12:01 AM

C and C play a vital role in the JavaScript engine, mainly used to implement interpreters and JIT compilers. 1) C is used to parse JavaScript source code and generate an abstract syntax tree. 2) C is responsible for generating and executing bytecode. 3) C implements the JIT compiler, optimizes and compiles hot-spot code at runtime, and significantly improves the execution efficiency of JavaScript.

JavaScript in Action: Real-World Examples and ProjectsJavaScript in Action: Real-World Examples and ProjectsApr 19, 2025 am 12:13 AM

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

JavaScript and the Web: Core Functionality and Use CasesJavaScript and the Web: Core Functionality and Use CasesApr 18, 2025 am 12:19 AM

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)