rxjs angular_Angular RxJS深度

rxjs angular

In this tutorial, we'll learn to use the RxJS 6 library with Angular 6 or Angular 7. We'll learn about:

在本教程中,我們將學習將RxJS 6庫與Angular 6或Angular 7結合使用。我們將了解:

  • How to import the Observable class and the other operators.

    如何導入Observable類和其他運算符。
  • How to subscribe and unsubscribe from Observables.

    如何訂閱和取消訂閱Observables。
  • How to import and call operators and chain them with the pipe() function.

    如何導入和調用運算符以及如何使用pipe()函數將它們鏈接在一起。

  • We'll also see how to use the async pipe to subscribe to Observables from Angular templates.

    我們還將看到如何使用異步管道從Angular模板訂閱Observable。
  • Finally we'll see how to use some popular pipeable operators such as tap(), map() and filter() and their new import paths in RxJS 6.

    最后,我們將了解如何在RxJS 6中使用一些流行的可管道運算符,例如tap()map()filter()以及它們的新導入路徑。

Note: This tutorial works with both Angular 6 and Angular 7.

注意 :本教程適用于Angular 6和Angular 7。

Throughout this tutorial, we’ll start looking at what reactive programming, asynchronous operations and data streams are and how they are related to the RxJS library. We’ll then see the concept of an RxJS Observable with examples, the various types of Observables such as:

在整個教程中,我們將開始研究什么是React式編程,異步操作和數據流,以及它們與RxJS庫的關系。 然后,我們將通過示例,各種類型的Observable來了解RxJS Observable的概念,例如:

  • Subject,

    Subject

  • BehaviorSubject and ReplaySubject,

    BehaviorSubjectReplaySubject

  • unicast and multicast Observables,

    單播和多播Observable,
  • cold and hot Observables ?etc.

    冷和熱可觀察物等

Next, we’ll see what RxJS operators are and examples of some popular operators such as tap(), map(), filter(), share(), etc. And finally we’ll see how Angular uses the RxJS Observable to do asynchronous programming.

接下來,我們將看到RxJS運算符是什么,以及一些流行的運算符的示例,例如tap()map()filter()share()等。最后,我們將了解Angular如何使用RxJS Observable來進行操作異步編程。

什么是React式編程 (What is Reactive Programming)

Let’s see the definition of Reactive programming from different sources.

讓我們看看來自不同來源的React式編程的定義。

This is how ?Andre Staltz, the creator of cycle.js (A functional and reactive JavaScript framework for predictable code) defines it:

這就是cycle.js (可預測代碼的功能性和React性JavaScript框架)的創建者Andre Staltz定義它的方式:

Reactive Programming is programming with asynchronous data streams

React式編程是使用異步數據流進行編程

This means when you are writing code that deals with asynchronous operations and streams of data, you are doing reactive programming.

這意味著當您編寫處理異步操作和數據流的代碼時,您正在執行React式編程。

Now, this is the definition from Wikipedia which is more in-depth:

現在,這是來自維基百科的更深入的定義:

In computing, reactive programming is a declarative programming paradigm concerned with data streams and the propagation of change.

在計算中,React式編程是與數據流和變化的傳播有關的聲明式編程范例。

This means reactive programming is a declarative (vs. a procedural) style of programming ?that works on streams of data.

這意味著響應式編程是一種聲明式(相對于過程式)的編程風格,適用于數據流。

For a detailed guide on reactive programming and data streams, check out: The introduction to Reactive Programming you've been missing.

有關React式編程和數據流的詳細指南,請查看: 您缺少關于React式編程的介紹 。

What is Stream

什么是流

A stream is an essential concept in reactive programming so it's worth seeing the definition before we proceed further.

在響應式編程中,流是必不可少的概念,因此在繼續進行之前,有必要先看一下定義。

In all definitions we’ve seen the word stream.

在所有定義中,我們都看到了詞流。

So what is a stream?

那么什么是流?

Simply put:

簡單的說:

A stream refers to values of data overtime.

流是指數據超時的值。

We'll see later that Observables and streams are very related concepts.

稍后我們將看到Observable和流是非常相關的概念。

什么是RxJS (What is RxJS)

Now, that we’ve seen the conceps of reactive programming and data streams, let’s see what RxJS is.

現在,我們已經看到了React式編程和數據流的概念,讓我們看看RxJS是什么。

RxJS is a popular library among web developers. It provides functional and reactive programming patterns for working with events and streams of data and has been integrated in many web development libraries and frameworks such as Angular.

RxJS是Web開發人員中流行的庫。 它提供了用于處理事件和數據流的功能性和React性編程模式,并且已集成到許多Web開發庫和框架(例如Angular)中。

RxJS makes it easy for JavaScript developers to write asynchronous code using composable Observables instead of callbacks and Promises.

RxJS使JavaScript開發人員可以輕松地使用可組合的Observable而不是回調和Promises編寫異步代碼。

RxJS stands for Reactive Extensions for JavaScript and it actually has implementations in other programming languages such as Java, Python, Ruby, and PHP etc. It's also available for platforms such as Android. Check out the complete list of supported languages and platforms.

RxJS代表JavaScript的Reactive Extensions,它實際上具有其他編程語言(例如Java,Python,Ruby和PHP等)的實現。它也可用于Android等平臺。 查看支持的語言和平臺的完整列表 。

RxJS v6 is currently the stable version of RxJS and it has many breaking changes with RxJS v5. You can check out more information about the changes and how to migrate from the old version from this official migration guide.

RxJS v6當前是RxJS的穩定版本,并且在RxJS v5中有許多重大更改。 您可以從本官方遷移指南中查看有關更改以及如何從舊版本進行遷移的更多信息。

RxJS 6 has many advantages over the previous RxJS 5 version(s), such as:

與以前的RxJS 5版本相比,RxJS 6具有許多優點,例如:

  • The bundle size of the library is smaller,

    庫的捆綁包尺寸較小,
  • The performance of the latest version is better,

    最新版本的性能更好,
  • RxJS 6 Observable follows the Observable Spec Proposal,

    RxJS 6 Observable遵循Observable Spec Proposal ,

  • The latest version provides better debugability,

    最新版本提供了更好的可調試性,
  • A better modular architecture,

    更好的模塊化架構,
  • It's backward compatible.

    向后兼容。

如何安裝和使用RxJS (How to Install and Use RxJS)

RxJS is a JavaScript library which means you can install it in the same way you install other libraries:

RxJS是一個JavaScript庫,這意味著您可以使用與安裝其他庫相同的方式來安裝它:

Using RxJS with ES6 via npm

通過npm在ES6中使用RxJS

In your project, you can run the following command to install RxJS:

在您的項目中,您可以運行以下命令來安裝RxJS:

$ npm install rxjs

You can then import the symbols you want to use from the rxjs package or a sub-package such as rxjs/operators:

然后,您可以從rxjs包或子包(例如rxjs/operators導入要使用的符號:

import { Observable, Subscriber } from 'rxjs';
import { tap, map, filter } from 'rxjs/operators';

We imported the Observable and Subscriber symbols from rxjs and the tap, map and filter operators from rxjs/operators.

我們從rxjs導入了ObservableSubscriber符號,并從rxjs/operators導入了tapmapfilter運算rxjs/operators

We'll see later what these symbols are and how to use them in your Angular application.

稍后我們將看到這些符號是什么以及如何在Angular應用程序中使用它們。

Using RxJS from a CDN

從CDN使用RxJS

You can also use RxJS from a CDN using a <script> in your HTML document:

您還可以使用HTML文檔中的<script>從CDN使用RxJS:

<script src="https://unpkg.com/rxjs/bundles/rxjs.umd.min.js"></script>

Note: Please note that in Angular 6 & 7, RxJS 6 is already included in your project so you don't need to install it manually.

注意 :請注意,在Angular 6和7中,RxJS 6已包含在您的項目中,因此您無需手動安裝它。

RxJS 6中的什么是可觀察,觀察者和訂閱 (What is an Observable, Observer and Subsription in RxJS 6)

RxJS uses the concept of Observables to handle and work with asynchronous and event-based code.

RxJS使用Observables的概念來處理和使用基于事件的異步代碼。

The asynchronous word comes from Asynchrony. In computer programming, here is the definition of Asynchrony from Wikipedia:

異步字來自異步。 在計算機編程中,這是維基百科中異步的定義:

Asynchrony, in computer programming, refers to the occurrence of events independent of the main program flow and ways to deal with such events. These may be "outside" events such as the arrival of signals, or actions instigated by a program that take place concurrently with program execution, without the program blocking to wait for results.

在計算機編程中,異步是指事件的發生與主程序流以及處理此類事件的方式無關。 這些可能是“外部”事件,例如信號的到來,或與程序執行同時發生的由程序引發的動作,而程序不會阻塞等待結果。

After reading this definition, you may have concluded how much asynchrony is important for computers and programming!

閱讀此定義后,您可能已經得出結論,異步對于計算機和編程而言很重要!

Let's make this simple!

讓我們簡單點吧!

Asynchronous code is the inverse of synchronous code which is the original way of thinking about your code when you are first introduced to programming.

異步代碼是同步代碼的逆過程,這是您初次接觸編程時對代碼進行思考的原始方式。

Your code is synchronous when it's running in sequences i.e instruction by instruction in the order they appear in the source code.

當您的代碼按順序運行時,即按它們在源代碼中出現的順序逐條指令運行時,它們是同步的。

For example, let's consider this simple JavaScript code:

例如,讓我們考慮以下簡單JavaScript代碼:

const foo = "foo" //1
const bar = "bar" //2
const foobar = foo  +  bar //3
console.log(foobar) //4

The browser will run this synchronous code line by line from line 1 to 4 starting by assigning the foo and bar variables, concatenating them and displaying the foobar variable in the console.

瀏覽器將從第1行到第4行逐行運行此同步代碼,首先分配foobar變量,將它們連接起來并在控制臺中顯示foobar變量。

JavaScript supports also the asynchronous approach of writing code which makes sense, since you need to respond to the user events in the browser but you don't actually know when the user interacts with your application (and in which order) when you are writing code.

JavaScript還支持有意義的異步代碼編寫方法,因為您需要在瀏覽器中響應用戶事件,但實際上您不知道用戶何時在與您的應用程序交互(以及順序如何) 。

This was originally achieved using callbacks which you need to define in your code and specify when they will be called.

這最初是使用回調實現的,您需要在代碼中定義這些回調并指定何時調用它們。

For example, the following asynchronous code will display You clicked the button! when the user clicks the button identified by the mybutton identifier:

例如,以下異步代碼將顯示您單擊了按鈕! 當用戶單擊由mybutton標識符標識的按鈕時:

document.getElementById('mybutton').addEventListener('click', () => {console.log("You clicked the button!")
})

The second argument of the addEventListener() method is the callback.

addEventListener()方法的第二個參數是回調。

You can also use callbacks to handle asynchronous operations which don't involve the DOM. For example, the following code can be used to send an HTTP POST request to a web server:

您還可以使用回調來處理不涉及DOM的異步操作。 例如,以下代碼可用于將HTTP POST請求發送到Web服務器:

const xhr = new XMLHttpRequest()
xhr.onreadystatechange = () => {if (xhr.readyState === 4) {xhr.status === 200 ? console.log(xhr.responseText) : console.error('error')}
}
xhr.open('POST', 'your.server.com')
xhr.send()

This is how you perform the famous Ajax calls in JavaScript.

這就是在JavaScript中執行著名的Ajax調用的方式。

Actually, Ajax itself stands for Asynchronous JavaScript and XML.

事實上, 阿賈克斯本身代表同步?avaScript 一個X ML。

Note: Sending HTTP requests (which is a common operation in web apps) is an asynchronous operation by nature since the request will take time to reach the server which will then send a response back to your client application. In this mean time, the application needs to respond to other actions and perform other tasks and only process the server response when it's received.

注意 :發送HTTP請求(這是Web應用程序中的常見操作)本質上是異步操作,因為請求將花費一些時間到達服務器,然后服務器將響應發送回客戶端應用程序。 同時,應用程序需要響應其他操作并執行其他任務,并且僅在收到服務器響應后才對其進行處理。

If you have ever extensively worked with callbacks, you'll notice one problem with them. They are difficult to track!

如果您曾經廣泛使用過回調,您會發現它們存在一個問題。 他們很難追蹤!

When you write complex applications you usually end up writing nested callbacks (callbacks inside callbacks) with multiple nesting levels. This is what's known as the callback hell.

當您編寫復雜的應用程序時,通常最終會編寫具有多個嵌套級別的嵌套回調(回調內部的回調)。 這就是所謂的回調地獄 。

Modern JavaScript introduced other approaches or abstractions to deal with asynchronous operations (without using too much callbacks) such as Promises and Async/Await.

現代JavaScript引入了其他方法或抽象來處理異步操作(不使用過多的回調),例如Promises和Async / Await。

Promises have been introduced in ES6 (JS 2015).

在ES6 (JS 2015)中引入了承諾。

Async/await has been introduced in ES8 (JS 2017) and it's actually a syntactic sugar on top of Promises which helps developers write asynchronous code with Promises in a way that looks synchronous.

Async / await已在ES8(JS 2017)中引入,它實際上是Promises之上的語法糖,它可以幫助開發人員以看上去同步的方式使用Promises編寫異步代碼。

But Promises are actually similar to callbacks and have the same nesting problem at some degree.

但是Promises實際上類似于回調,并且在某種程度上具有相同的嵌套問題。

Since developers are always looking for better solutions we now have Observables which use the observer software pattern.

由于開發人員一直在尋找更好的解決方案,因此我們現在有了使用觀察者軟件模式的Observables。

The observer pattern is a software design pattern in which an object, called the subject, maintains a list of its dependents, called observers, and notifies them automatically of any state changes, usually by calling one of their methods. Observer pattern.

觀察者模式是一種軟件設計模式,其中一個稱為主題的對象會維護其依賴者的列表(稱為觀察者),并通常通過調用其方法之一來自動將狀態更改通知他們。 觀察者模式 。

Observables are implemented in the ReactiveX project which has implementations in various languages. RxJS is the JavaScript implementation.

可觀察對象在ReactiveX項目中實現,該項目具有各種語言的實現。 RxJS是JavaScript實現。

Note: Observables are implemented in many other libraries such as zen-observable and xstream but RxJS Observables are the most popular in JavaScript.

注意 :Observables在許多其他庫中實現,例如zen-observable和xstream,但是RxJS Observables在JavaScript中最受歡迎。

Observables are not yet a builtin feature of JavaScript but there is a proposal to add them in EcmaScript.

可觀察對象還不是JavaScript的內置功能,但是建議將其添加到EcmaScript中。

Now, what's an RxJS Observable?

現在,什么是RxJS Observable?

An Observable is an entity that emits (or publishes) multiple data values (stream of data) over time and asynchronously.

一個Observable是一個實體,它隨時間推移并異步地發出(或發布)多個數據值(數據流)。

This is the definition of an Observable from the RxJS docs

這是RxJS文檔中 Observable的定義

Observable represents the idea of an invokable collection of future values or events.

可觀察表示未來值或事件的可調用集合的想法。

Observers and Subscriptions

觀察者和訂閱

There are also related concepts that you'll work with when using Observables which are Observers and Subscriptions.

使用Observable( 觀察者訂閱)時,還需要處理一些相關概念。

Observers are also called listeners (or consumers) as they can listen or subscribe to get the observed data.

觀察者也稱為偵聽器(或使用者),因為他們可以偵聽或訂閱以獲取觀察到的數據。

From the RxJS docs:

從RxJS文檔中:

Observer is a collection of callbacks that knows how to listen to values delivered by the Observable.

Observer是一組回調,它們知道如何偵聽Observable傳遞的值。

Subscriptions are objects that are returned when you subscribe to an Observable. They contain many methods such as the unsubscribe() method that you can call to unsubscribe from receving published values from the Observable.

訂閱是您訂閱Observable時返回的對象。 它們包含許多方法,例如unsubscribe()方法,您可以調用這些方法來取消訂閱以從Observable中檢索發布的值。

From the official docs:

從官方文檔:

Subscription represents the execution of an Observable, is primarily useful for cancelling the execution.

訂閱表示Observable的執行,主要用于取消執行。

RxJS中的主題是什么 (What is a Subject in RxJS)

A Subject is a special type of Observable that observers can also subscribe to it to receive published values but with one difference: ?The values are multicasted to many Observers.

主題是Observable的一種特殊類型,觀察者也可以訂閱它以接收已發布的值,但有一個區別: 值被多播到許多Observers上

Note: By default an RxJS Observable is unicast.

注意 :默認情況下,RxJS Observable是單播的。

Unicast simply means that each subscribed observer has an independent execution of the Observable while multicast means that the Observable execution is shared by multiple Observers.

單播僅表示每個訂閱的觀察者對Observable具有獨立的執行,而多播則意味著多個觀察者共享Observable的執行。

Note: Subjects are similar to Angular EventEmitters.

注意 :主題類似于Angular EventEmitters。

So when using Subjects instead of plain Observables, all subscribed Observers will get the same values of emitted data.

因此,當使用Subject而不是普通Observable時,所有訂閱的Observer都將獲得相同的發射數據值。

Note: Subjects are also Observers i.e they can also subscribe to other Observables and listen to published data.

注意 :主題也是觀察者,即他們也可以訂閱其他可觀察對象并收聽發布的數據。

Hot and Cold Observables

冷熱觀測

Unlike regular Observables, Subjects are called hot. ?A hot Observable starts emitting events even before any observer subscribes to it which means observers may lose previous emitted values if they don’t subscribe at that right time while cold Observables ****start emitting values when at least one observer is subscribed.

與常規的Observables不同,Subject被稱為hot 。 一個熱的Observable甚至在任何觀察者訂閱之前就開始發出事件,這意味著如果觀察者在正確的時間不進行訂閱,則觀察者可能會丟失先前發出的值,而冷的 Observable則在至少一個觀察者被訂閱時才開始發出值。

Note: You can use the asObservable() method to convert a subject to only an Observable.

注意 :可以使用asObservable()方法將主題轉換為僅可觀察的對象。

RxJS的BehaviorSubjectReplaySubject (RxJS’ BehaviorSubject and ReplaySubject)

RxJS provides two other types of Subjects: BehaviorSubject and ReplaySubject.

RxJS提供了另外兩種類型的主題: BehaviorSubjectReplaySubject

With a normal Subject, Observers that are subscribed at a point later will not receive data values emitted before their subscriptions. In many situations, this is not the desired behavior we want to implement. This can be solved using ?BehaviorSubject and ReplaySubject.

對于普通主題,稍后在某個點訂閱的觀察者將不會接收在訂閱之前發出的數據值。 在許多情況下,這不是我們想要實現的期望行為。 可以使用BehaviorSubjectReplaySubject解決。

ReplaySubject works by using a buffer that keeps the emitted values and re-emit them when new Observers are subscribed.

ReplaySubject通過使用緩沖區來工作,該緩沖區保留發出的值并在訂閱新的Observer時重新發射它們。

BehaviorSubject works like ReplaySubject but only re-emits the last emitted value.

BehaviorSubject工作方式類似于ReplaySubject但僅重新發出最后發出的值。

如何創建可觀察的RxJS (How to Create an RxJS Observable)

You can create an RxJS Observable using the Observable.create() method which takes a function with an observer argument. You can then subscribe to the returned Observable instance.

您可以使用Observable.create()方法創建RxJS Observable,該方法采用帶有observer參數的函數。 然后,您可以訂閱返回的Observable實例。

There many other methods to create Observables besides the static create() method:

除了靜態create()方法之外,還有許多其他方法可以創建Observables:

  • The lift() instance method which creates a new Observable from the instance (the source) it's called on,

    lift()實例方法,可從調用該實例的實例(源)創建一個新的Observable,

  • The of([]) operator which creates an Observable of a single value. We'll see an example next,

    of([])運算符,它創建單個值的Observable。 接下來,我們將看一個示例,

  • The interval(interval) operator which creates an Observable that emits an infinite sequence of numbers. Each number is emitted at a constant interval of time in seconds,

    創建一個Observable的interval(interval)運算符發出一個無窮大的數字序列。 每個數字都會以固定的時間間隔(以秒為單位)發出,

  • The timer() operator which returns an Observable that after a specified amount of time, emits numbers in sequence every specified duration,

    timer()運算符,它返回一個Observable,在指定的時間量后,它在每個指定的持續時間內依次發出數字,

  • The from() method that creates an Observable from a Promise or an array of values,

    from() Promise或值數組創建Observable的from()方法,

  • The fromEvent() method that creates an Observable from a DOM event,

    從DOM事件創建Observable的fromEvent()方法,

  • The ajax() method which creates an Observable that sends an Ajax request.

    創建一個發送一個Ajax請求的Observable的ajax()方法。

We'll see these creation methods by example later.

我們將在后面的示例中看到這些創建方法。

如何訂閱可觀察的RxJS (How to Subscribe to an RxJS Observable)

After creating an Observable, you can subscribe to it using the subscribe() method on the instance which returns an instance of Subscription.

創建Observable ,可以在實例上使用Subscription subscribe()方法對其進行預訂,該方法返回Subscription的實例。

RxJS可觀察的簡單示例 (A Simple Example of the RxJS Observable)

Let's now see a simple example of creating and working with an Observable.

現在,讓我們看一個創建和使用Observable的簡單示例。

First let's create an Observable:

首先讓我們創建一個Observable:

let ob$ = Observable.create((observer) => {observer.next("A new value!");
});

We create an ob$ Observable and we define the logic that our Observable is supposed to do in the body of the passed in method.

我們創建一個ob$ Observable,然后在傳入的方法的主體中定義Observable應該執行的邏輯。

In this example, the Observable will simply emit the A new value! value to the subscribed Observer.

在此示例中,Observable將僅發出A新值! 值給訂閱的觀察者。

Note: The dollar sign is just a convention for naming variables that hold instance of Observables.

注意 :美元符號只是用于命名包含Observables實例的變量的約定。

We call the next() method of the observer object to inform it of the available values.

我們調用觀察者對象的next()方法來通知它可用的值。

Note: All observer objects must have a collection of methods such as next(), complete() and error(). This allows Observables to communicate with them.

注意 :所有觀察者對象都必須具有方法的集合,例如next()complete()error() 。 這使Observable可以與它們進行通信。

The next() method is used by the Observable to pass values (publish values) to the subscribed Observer.

Observable使用next()方法將值(發布值)傳遞給訂閱的Observer。

Next, let's create an observer object:

接下來,讓我們創建一個觀察者對象:

let observer = {next: data => console.log( 'Data received: ', data),complete: data => console.log('Completed'),
};

An observer is a plain JavaScript object that contains methods such as next(), complete() and error(). This means it knows how to get notified by the Observable.

觀察者是一個普通JavaScript對象,其中包含next()complete()error() 。 這意味著它知道如何通過Observable進行通知。

Note: You can also add other custom attributes and methods to the Observer objects besides next(), complete() and error().

注意 :除了next()complete()error()之外,還可以向Observer對象添加其他自定義屬性和方法。

Finally, let's subscribe to our ob$ Observable and return a Subscription:

最后,讓我們訂閱我們的ob$ Observable并返回一個Subscription

let subscription = ob$.subscribe(observer);

Once you susbscribe to the ob$ Observable, you'll get the following output in the console:

懷疑ob$ Observable后,您將在控制臺中獲得以下輸出:

Data received: A new value!

RxJS運算符 (RxJS Operators)

RxJS provides the implemenation of Observable concept but also a variety of operators that allows you to compose Observables.

RxJS提供了Observable概念的實現,但還提供了多種運算符,使您可以編寫Observable。

Operators offer a declarative way to perform complex asynchronous operations with Observables.

運算符提供了一種聲明性的方式來使用Observables執行復雜的異步操作。

An operator works on a source Observable by observing its emitted values and applying the intended transformation on them then return a new Observable with the modified values.

操作員通過觀察源的發射值并對其進行預期的轉換來對源Observable進行操作,然后返回具有已修改值的新Observable。

There many RxJS operators such as:

RxJS運算符很多,例如:

  • tap(),

    tap()

  • map(),

    map()

  • filter(),

    filter()

  • concat(),

    concat()

  • share(),

    share()

  • retry(),

    retry()

  • catchError(),

    catchError()

  • switchMap(),

    switchMap()

  • and flatMap() etc.

    flatMap()等。

管道:結合多個運算符 (Pipes: Combining Multiple Operators)

RxJS provides two versions of the pipe() function: A standalone function and a method on the Observable interface.

RxJS提供了pipe()函數的兩個版本:獨立函數和Observable接口上的方法。

You can use the pipe() function/method to combine multiple Operators. For example:

您可以使用pipe()函數/方法來組合多個運算符。 例如:

import { filter, map } from 'rxjs/operators';
const squareOf2 = of(1, 2, 3, 4, 5,6).pipe(filter(num => num % 2 === 0),map(num => num * num));
squareOf2.subscribe( (num) => console.log(num));

The of() method will create and return an Observable from the 1, 2, 3, 4, 5,6 numbers and the pipe() method will apply the filter() and map() operators on each emitted value.

of()方法將根據1, 2, 3, 4, 5,6數字創建并返回一個Observable 1, 2, 3, 4, 5,6pipe()方法將在每個發射值上應用filter()map()運算符。

如何在Angular中使用Observable (How Observables are Used in Angular)

Angular uses the RxJS Observable as a built-in type for many of its APIs such as:

Angular使用RxJS Observable作為其許多API的內置類型,例如:

  • The HttpClient methods return Observables and actual requests are only sent when you subscribe to the returned Observable.

    HttpClient方法返回Observables,只有在您訂閱返回的Observable時才發送實際請求。

  • The Router uses Observables in multiple places such as:

    路由器在多個位置使用Observable,例如:
  • the [events](https://angular.io/api/router/Router#events) of the Router instance is an Observable to listen to events on the router.

    路由器實例的[events](https://angular.io/api/router/Router#events)是一個可觀察到的事件,用于偵聽路由器上的事件。

  • Also ActivatedRoute (which contains information about the route associated with the currently loaded component on the router outlet) has many Observable properties such as params and paramMap for the route parameters.

    另外ActivatedRoute (包含有關與路由器出口上當前加載的組件關聯的路由的信息)也具有許多可觀察的屬性,例如,用于路由參數的paramsparamMap

Let's assume, you have an Angular component and the Router service injected as router. This example from StackOverflow shows you how you can subscribe to the router events for detecting a route change:

假設您有一個Angular組件,并且將Router服務注入為router 。 StackOverflow的以下示例向您展示了如何訂閱路由器事件以檢測路由更改:

import { Component } from '@angular/core'; 
import { Router, Event, NavigationStart, NavigationEnd, NavigationError } from '@angular/router';
@Component({selector: 'app-root',template: `<router-outlet></router-outlet>`
})
export class AppComponent {constructor(private router: Router) {this.router.events.subscribe((event: Event) => {if (event instanceof NavigationStart) {console.log("Navigation start");}if (event instanceof NavigationEnd) {console.log("Navigation end");}if (event instanceof NavigationError) {console.log(event.error);}});}
}
  • The Reactive Forms Module uses reactive programming and Observables for listening to user input.

    響應式表單模塊使用響應式編程和Observables來偵聽用戶輸入。
  • The @output() decorator in a component takes an EventEmitter instance. EventEmitter is a subclass of the RxJS Observable.

    組件中的@output()裝飾器采用EventEmitter實例。 EventEmitter是RxJS Observable的子類。

如何在角度代碼中使用RxJS 6 Observable (How to Use RxJS 6 Observable in Your Angular Code)

Angular uses Observables (implemented with the RxJS library) for all asynchronous events. If you are using Angular CLI 6|7, RxJS 6 will be installed by default on your project.

Angular對所有異步事件都使用Observables(由RxJS庫實現)。 如果您使用的是Angular CLI 6 | 7,則默認情況下將在項目上安裝RxJS 6。

Otherwise you can install it via npm using:

否則,您可以使用以下方法通過npm安裝它:

$ npm install rxjs --save

To be able to use the Observable symbol in your code, you first need to import it:

為了能夠在代碼中使用Observable符號,首先需要將其導入:

import { Observable } from 'rxjs';

This is the new import path in RxJS 6 which is different from RxJS 5.

這是RxJS 6中與RxJS 5不同的新導入路徑。

使用HttpClient模塊和Observables (Working with the HttpClient Module and Observables)

The new Angular HttpClient works with Observables by default. Methods such as get(), post(), put() and delete() return an instance of the Observable interface.

默認情況下,新的Angular HttpClient與Observables一起使用。 get()post()put()delete()返回Observable接口的實例。

HTTP requests are only sent when we subscribe to the Observable.

僅當我們訂閱Observable時才發送HTTP請求。

This is an example of making an HTTP request:

這是發出HTTP請求的示例:

getItems(): Observable<Item[]> {return this.httpClient.get<Item[]>(this.itemUrl);
}

We assume that you have injected the HttpClient service as httpClient.

我們假設您已將HttpClient服務注入為httpClient

AsyncPipe使用Observable (Using Observable with AsyncPipe)

Angular AsyncPipe subscribes to Observable and returns the emitted data. For example. Let's suppose we have this method:

Angular AsyncPipe訂閱Observable并返回發出的數據。 例如。 假設我們有這種方法:

getItems(): Observable {this.items$ = this.httpClient.get(this.itemUrl);
}

The items$ variable is of type Observable<Item[]>`.

items$變量的類型為Observable <Item []>`。

After calling the getItems() method on the component we can use the async pipe in the component template to subscribe to the returned Observable:

在組件上調用getItems()方法后,我們可以使用組件模板中的async管道來訂閱返回的Observable:

訂閱可觀察物 (Subscribing to Observables)

Observables are used for better support of event handling, asynchronous programming, and handling multiple values. When you define an Observable to publish some values for a consumer, the values are not emitted until you actually subscribe to the Observable.

可觀察變量用于更好地支持事件處理,異步編程以及處理多個值。 當您定義一個Observable來為使用者發布一些值時,這些值直到您實際訂閱Observable時才會發出。

The Consumer that subscribes to the Observable keeps receiving values until the Observable is completed or the consumer unsubscribes from the observable.

訂閱可觀察對象的消費者將繼續接收值,直到該可觀察對象完成或消費者不再訂閱該可觀察對象。

Let's start by defining an observable that provides a stream of updates

讓我們開始定義一個可觀察的對象,它提供更新流

使用map()運算符 (Using the map() Operator)

The map() operator is similar to the Array.map() method. It lets you map observable responses to other values. For example:

map()運算符類似于Array.map()方法。 它使您可以將可觀察到的響應映射到其他值。 例如:

import { Observable} from 'rxjs';
import { map } from 'rxjs/operators';
getItems(): Observable> {return this.aService.getItems().pipe(map(response => response.data));
}

The getItems() method returns an Observable. We're using the map() operator to return the data property of the response object.

getItems()方法返回一個Observable。 我們正在使用map()運算符返回響應對象的data屬性。

The operator enables us to map the response of the Observable stream to the data value.

運算符使我們能夠將Observable流的響應映射到data值。

We import the pipeable operator map() from the rxjs/operators package and we use the pipe() method (which takes a variable number of pipeable operators) to wrap the operator.

我們從rxjs/operators包中導入可管道運算符map() ,并使用pipe()方法(采用可變數量的可管道運算符)包裝該運算符。

使用filter()運算符 (Using the filter() Operator)

The filter() operator is similar to the Array.filter() method. It lets you filter the observable stream and returns another observable. For example:

filter()運算符類似于Array.filter()方法。 它使您可以過濾可觀察的流并返回另一個可觀察的流。 例如:

import { Observable} from 'rxjs';
import { filter } from 'rxjs/operators';filter(): Observable<Array<any>> {return this.aService.getItems().pipe(filter(response => response.code === 200));
}

We use the ?filter() operator to only emit a notification to observers of the observable stream when the status code of the HTTP response is 200.

當HTTP響應的狀態碼為200時,我們使用filter()運算符僅向可觀察流的觀察者發出通知。

結論 (Conclusion)

In this tutorial, you have been introduced to reactive programming, data streams and RxJS 6.

在本教程中,向您介紹了React式編程,數據流和RxJS 6。

You have learned that reactive programming is about coding with asynchronous data streams and that RxJS is the most popular implementation that implements Observables and the observer pattern.

您已經了解到,React式編程是關于使用異步數據流進行編碼,并且RxJS是實現Observables和觀察者模式的最流行的實現。

You have learned what an Observable is — An object that emits or publishes values over time and asynchronously.

您已經了解了什么是Observable-隨時間推移以異步方式發出或發布值的對象。

You have learned about the related concepts to Observables such as Observers and Subscriptions — Observers are objects that listen and consume values published by an Observable and Subscriptions are the objects returned from the subscribe() method (They are usually used to unsubscribe the Observer from the Observable).

您已經了解了與Observables相關的概念,例如Observers和Subscriptions-Observers是偵聽和使用Observable發布的值的對象,Subscriptions是從subscription subscribe()方法返回的對象(它們通常用于從Observable取消訂閱Observer。可觀察到的)。

You have also learned about special types of Observables such as Subjects, behavior Subjects (BehaviorSubject) and replay Subjects (ReplaySubject) and also the difference between unicast and multicast Observables. As a reminder a multicast Observable shares its execution between all its Observers.

您還了解了特殊類型的Observable,例如主題,行為主題( BehaviorSubject )和重播主題( ReplaySubject ),以及單播和多播Observable之間的區別。 提醒一下,多播Observable在其所有觀察者之間共享其執行。

You learned about cold and hot Observables — hot refers to when the Obseravble starts publishing values when it’s created even before getting any subscriptions.

您了解了冷的和熱的Observables-hot是指Obseravble在創建值時開始發布值的時間,甚至在獲得任何訂閱之前。

You learned about RxJS operators which are methods that are used to compose Observables and work on their data streams.

您了解了RxJS運算符,它們是用于構成Observable并對其數據流進行處理的方法。

Finally, you learned that Angular 6 & 7 uses RxJS v6 for working with asynchronous operations and APIs (instead of callbacks or Promises) in many of its commonly used modules such as HttpClient, Router and ReactiveForms.

最后,您了解到Angular 6和7在其許多常用模塊(例如HttpClientRouterReactiveForms )中使用RxJS v6處理異步操作和API(而不是回調或Promises)。

This article was originally posted in techiediaries.

本文最初發表在技術文章上 。

翻譯自: https://www.freecodecamp.org/news/angular-rxjs-in-depth/

rxjs angular

本文來自互聯網用戶投稿,該文觀點僅代表作者本人,不代表本站立場。本站僅提供信息存儲空間服務,不擁有所有權,不承擔相關法律責任。
如若轉載,請注明出處:http://www.pswp.cn/news/391107.shtml
繁體地址,請注明出處:http://hk.pswp.cn/news/391107.shtml
英文地址,請注明出處:http://en.pswp.cn/news/391107.shtml

如若內容造成侵權/違法違規/事實不符,請聯系多彩編程網進行投訴反饋email:809451989@qq.com,一經查實,立即刪除!

相關文章

HashMap, LinkedHashMap 和 TreeMap的區別

HashMap, LinkedHashMap 和 TreeMap的區別 Java里面的HashMap, LinkedHashMap 和 TreeMap 有什么區別?我看不出以下3個key和value有什么不同的。Hashtables里面又是怎么樣的呢&#xff1f; Map m1 new HashMap(); m1.put("map", "HashMap"); m1.put(&q…

“陪護機器人”研報:距離真正“陪護”還差那么一點

一款有“缺陷”的機器人&#xff0c;怎能做到真正的“陪護”&#xff1f; 近日&#xff0c;鼎盛智能發布了一款名為Ibotn的&#xff08;愛蹦&#xff09;幼兒陪伴機器人&#xff0c;核心看點就是通過人臉識別、場景識別等計算機視覺技術來實現機器人對兒童的陪護。不過&#xf…

neo-6m uno_Uno-統治所有人的平臺

neo-6m unoFirst, we should start off with what Uno is and why you should care. 首先&#xff0c;我們應該從Uno是什么以及為什么要關心開始。 As stated on their website, Uno is "The only platform for building native mobile, desktop and WebAssembly apps wi…

【轉】消息隊列應用場景

一、消息隊列概述 消息隊列中間件是分布式系統中重要的組件&#xff0c;主要解決應用耦合&#xff0c;異步消息&#xff0c;流量削鋒等問題。實現高性能&#xff0c;高可用&#xff0c;可伸縮和最終一致性架構。是大型分布式系統不可缺少的中間件。 目前在生產環境&#xff0c;…

JDK和JRE區別是什么

問題&#xff1a;JDK和JRE區別是什么 他們的角色分別是什么&#xff1f;我們應該什么時候使用他們&#xff1f; 回答一 JRE是Java Runtime Environment&#xff08;Java運行時環境&#xff09;。它是一個包&#xff0c;集合了運行一個編譯好的Java程序的一切必須的東西&…

樹莓派新手入門教程

http://www.ruanyifeng.com/blog/2017/06/raspberry-pi-tutorial.html

lime 模型_使用LIME的糖尿病預測模型解釋— OneZeroBlog

lime 模型Article outline文章大綱 Introduction 介紹 Data Background 資料背景 Aim of the article 本文的目的 Exploratory analysis 探索性分析 Training a Random Forest Model 訓練隨機森林模型 Global Importance 全球重要性 Local Importance 當地重要性 介紹 (Introd…

react 生命掛鉤_如何在GraphQL API中使用React掛鉤來管理狀態

react 生命掛鉤In this blog post, we are going to learn -在這篇博客中&#xff0c;我們將學習- What React hooks are 什么是React鉤子 How to use hooks for state management 如何使用掛鉤進行狀態管理 Before we start working with hooks, let us take a brief moment …

Linux第三周作業

1.三個法寶 ①存儲程序計算機工作模型&#xff0c;計算機系統最最基礎性的邏輯結構&#xff1b; ②函數調用堆棧&#xff0c;堆棧完成了計算機的基本功能&#xff1a;函數的參數傳遞機制和局部變量存取 &#xff1b; ③中斷&#xff0c;多道程序操作系統的基點&#xff0c;沒有…

什么時候使用靜態方法

問題&#xff1a;什么時候使用靜態方法 I am wondering when to use static methods? Say if I have a class with a few getters and setters, a method or two, and I want those methods only to be invokable on an instance object of the class. Does this mean I shou…

RESTful API淺談

2019獨角獸企業重金招聘Python工程師標準>>> 上半年時候&#xff0c;部門有組織的討論了一下實踐微服務的技術話題&#xff0c;主要內容是SOA服務和微服務各自的優勢和難點&#xff0c;其中有提到關于RESTful API設計方法。 正好最近在深入的學習HTTP協議&#xff0…

spring自動注入--------

<?xml version"1.0" encoding"UTF-8"?> <beans xmlns"http://www.springframework.org/schema/beans"xmlns:p"http://www.springframework.org/schema/p"xmlns:c"http://www.springframework.org/schema/c"xmlns…

變量的作用域和生存期:_生存分析簡介:

變量的作用域和生存期:In the previous article, I have described the Kaplan-Meier estimator. To give a quick recap, it is a non-parametric method to approximating the true survival function. This time, I will focus on another approach to visualizing a surviv…

數字孿生營銷_如何通過數字營銷增加您的自由職業收入

數字孿生營銷There are a lot of ways we could go with this topic as it’s a huge one, but I just want to cover the nuggets here and make it simple as well as practical to understand and implement.我們可以采用很多方法來處理這個主題&#xff0c;因為它是一個很大…

您的網卡配置暫不支持1000M寬帶說明

國內寬帶網速越來越快&#xff0c;運營商更是在今年初紛紛推進千兆寬帶業務。為了讓用戶更好地了解網絡狀況&#xff0c;360寬帶測速器發布新版&#xff0c;優化了寬帶測速范圍&#xff0c;可有效支持最高1000&#xff2d;的帶寬測量。此外&#xff0c;寬帶測速器能檢測用戶網卡…

教輔的組成(網絡流果題 洛谷P1231)

題目描述 蒟蒻HansBug在一本語文書里面發現了一本答案&#xff0c;然而他卻明明記得這書應該還包含一份練習題。然而出現在他眼前的書多得數不勝數&#xff0c;其中有書&#xff0c;有答案&#xff0c;有練習冊。已知一個完整的書冊均應該包含且僅包含一本書、一本練習冊和一份…

Java中怎么樣檢查一個字符串是不是數字呢

問題&#xff1a;Java中怎么樣檢查一個字符串是不是數字呢 在解析之前&#xff0c;怎么樣檢查一個字符串是不是數字呢 回答一 這些通常是由一個簡單的用戶自定義函數去解決的&#xff08;即&#xff0c;自帶的 “isNumeric” 函數&#xff09; 例如 public static boolean…

小程序支付api密鑰_如何避免在公共前端應用程序中公開您的API密鑰

小程序支付api密鑰問題 (The Problem) All you want to do is fetch some JSON from an API endpoint for the weather, some book reviews, or something similarly simple.您要做的就是從API端點獲取一些有關天氣的JSON&#xff0c;一些書評或類似的簡單內容。 The fetch qu…

永無止境_永無止境地死:

永無止境Wir befinden uns mitten in der COVID-19-Pandemie und damit auch im Mittelpunkt einer medialen Geschichte, die durch eine noch nie dagewesene Komplexitt und Dynamik gekennzeichnet ist. Wie kann Informationsdesign helfen, diese Explosion von Nachrich…

HDU4612 Warm up —— 邊雙聯通分量 + 重邊 + 縮點 + 樹上最長路

題目鏈接&#xff1a;http://acm.split.hdu.edu.cn/showproblem.php?pid4612 Warm up Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 65535/65535 K (Java/Others)Total Submission(s): 7206 Accepted Submission(s): 1681 Problem DescriptionN planets are …