javascript
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:
在本教程中,我們將學(xué)習(xí)將RxJS 6庫與Angular 6或Angular 7結(jié)合使用。我們將了解:
- How to import the Observable class and the other operators. 如何導(dǎo)入Observable類和其他運算符。
- How to subscribe and unsubscribe from Observables. 如何訂閱和取消訂閱Observables。
How to import and call operators and chain them with the pipe() function.
如何導(dǎo)入和調(diào)用運算符以及如何使用pipe()函數(shù)將它們鏈接在一起。
- 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()以及它們的新導(dǎo)入路徑。
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式編程,異步操作和數(shù)據(jù)流,以及它們與RxJS庫的關(guān)系。 然后,我們將通過示例,各種類型的Observable來了解RxJS Observable的概念,例如:
Subject,
Subject ,
BehaviorSubject and ReplaySubject,
BehaviorSubject和ReplaySubject ,
- 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來進(jìn)行操作異步編程。
什么是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 (可預(yù)測代碼的功能性和React性JavaScript框架)的創(chuàng)建者Andre Staltz定義它的方式:
Reactive Programming is programming with asynchronous data streams
React式編程是使用異步數(shù)據(jù)流進(jìn)行編程
This means when you are writing code that deals with asynchronous operations and streams of data, you are doing reactive programming.
這意味著當(dāng)您編寫處理異步操作和數(shù)據(jù)流的代碼時,您正在執(zhí)行React式編程。
Now, this is the definition from Wikipedia which is more in-depth:
現(xiàn)在,這是來自維基百科的更深入的定義:
In computing, reactive programming is a declarative programming paradigm concerned with data streams and the propagation of change.
在計算中,React式編程是與數(shù)據(jù)流和變化的傳播有關(guān)的聲明式編程范例。
This means reactive programming is a declarative (vs. a procedural) style of programming ?that works on streams of data.
這意味著響應(yīng)式編程是一種聲明式(相對于過程式)的編程風(fēng)格,適用于數(shù)據(jù)流。
For a detailed guide on reactive programming and data streams, check out: The introduction to Reactive Programming you've been missing.
有關(guān)React式編程和數(shù)據(jù)流的詳細(xì)指南,請查看: 您缺少關(guān)于React式編程的介紹 。
What is Stream
什么是流
A stream is an essential concept in reactive programming so it's worth seeing the definition before we proceed further.
在響應(yīng)式編程中,流是必不可少的概念,因此在繼續(xù)進(jìn)行之前,有必要先看一下定義。
In all definitions we’ve seen the word stream.
在所有定義中,我們都看到了詞流。
So what is a stream?
那么什么是流?
Simply put:
簡單的說:
A stream refers to values of data overtime.
流是指數(shù)據(jù)超時的值。
We'll see later that Observables and streams are very related concepts.
稍后我們將看到Observable和流是非常相關(guān)的概念。
什么是RxJS (What is RxJS)
Now, that we’ve seen the conceps of reactive programming and data streams, let’s see what RxJS is.
現(xiàn)在,我們已經(jīng)看到了React式編程和數(shù)據(jù)流的概念,讓我們看看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開發(fā)人員中流行的庫。 它提供了用于處理事件和數(shù)據(jù)流的功能性和React性編程模式,并且已集成到許多Web開發(fā)庫和框架(例如Angular)中。
RxJS makes it easy for JavaScript developers to write asynchronous code using composable Observables instead of callbacks and Promises.
RxJS使JavaScript開發(fā)人員可以輕松地使用可組合的Observable而不是回調(diào)和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等)的實現(xiàn)。它也可用于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當(dāng)前是RxJS的穩(wěn)定版本,并且在RxJS v5中有許多重大更改。 您可以從本官方遷移指南中查看有關(guān)更改以及如何從舊版本進(jìn)行遷移的更多信息。
RxJS 6 has many advantages over the previous RxJS 5 version(s), such as:
與以前的RxJS 5版本相比,RxJS 6具有許多優(yōu)點,例如:
- 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, 最新版本提供了更好的可調(diào)試性,
- A better modular architecture, 更好的模塊化架構(gòu),
- 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 rxjsYou can then import the symbols you want to use from the rxjs package or a sub-package such as rxjs/operators:
然后,您可以從rxjs包或子包(例如rxjs/operators導(dǎo)入要使用的符號:
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導(dǎo)入了Observable和Subscriber符號,并從rxjs/operators導(dǎo)入了tap , map和filter運算rxjs/operators 。
We'll see later what these symbols are and how to use them in your Angular application.
稍后我們將看到這些符號是什么以及如何在Angular應(yīng)用程序中使用它們。
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.
在計算機編程中,異步是指事件的發(fā)生與主程序流以及處理此類事件的方式無關(guān)。 這些可能是“外部”事件,例如信號的到來,或與程序執(zhí)行同時發(fā)生的由程序引發(fā)的動作,而程序不會阻塞等待結(jié)果。
After reading this definition, you may have concluded how much asynchrony is important for computers and programming!
閱讀此定義后,您可能已經(jīng)得出結(jié)論,異步對于計算機和編程而言很重要!
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.
異步代碼是同步代碼的逆過程,這是您初次接觸編程時對代碼進(jìn)行思考的原始方式。
Your code is synchronous when it's running in sequences i.e instruction by instruction in the order they appear in the source code.
當(dāng)您的代碼按順序運行時,即按它們在源代碼中出現(xiàn)的順序逐條指令運行時,它們是同步的。
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) //4The 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行逐行運行此同步代碼,首先分配foo和bar變量,將它們連接起來并在控制臺中顯示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還支持有意義的異步代碼編寫方法,因為您需要在瀏覽器中響應(yīng)用戶事件,但實際上您不知道用戶何時在與您的應(yīng)用程序交互(以及順序如何) 。
This was originally achieved using callbacks which you need to define in your code and specify when they will be called.
這最初是使用回調(diào)實現(xiàn)的,您需要在代碼中定義這些回調(diào)并指定何時調(diào)用它們。
For example, the following asynchronous code will display You clicked the button! when the user clicks the button identified by the mybutton identifier:
例如,以下異步代碼將顯示您單擊了按鈕! 當(dāng)用戶單擊由mybutton標(biāo)識符標(biāo)識的按鈕時:
document.getElementById('mybutton').addEventListener('click', () => {console.log("You clicked the button!") })The second argument of the addEventListener() method is the callback.
addEventListener()方法的第二個參數(shù)是回調(diào)。
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:
您還可以使用回調(diào)來處理不涉及DOM的異步操作。 例如,以下代碼可用于將HTTP POST請求發(fā)送到Web服務(wù)器:
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中執(zhí)行著名的Ajax調(diào)用的方式。
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.
注意 :發(fā)送HTTP請求(這是Web應(yīng)用程序中的常見操作)本質(zhì)上是異步操作,因為請求將花費一些時間到達(dá)服務(wù)器,然后服務(wù)器將響應(yīng)發(fā)送回客戶端應(yīng)用程序。 同時,應(yīng)用程序需要響應(yīng)其他操作并執(zhí)行其他任務(wù),并且僅在收到服務(wù)器響應(yīng)后才對其進(jìn)行處理。
If you have ever extensively worked with callbacks, you'll notice one problem with them. They are difficult to track!
如果您曾經(jīng)廣泛使用過回調(diào),您會發(fā)現(xiàn)它們存在一個問題。 他們很難追蹤!
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.
當(dāng)您編寫復(fù)雜的應(yīng)用程序時,通常最終會編寫具有多個嵌套級別的嵌套回調(diào)(回調(diào)內(nèi)部的回調(diào))。 這就是所謂的回調(diào)地獄 。
Modern JavaScript introduced other approaches or abstractions to deal with asynchronous operations (without using too much callbacks) such as Promises and Async/Await.
現(xiàn)代JavaScript引入了其他方法或抽象來處理異步操作(不使用過多的回調(diào)),例如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之上的語法糖,它可以幫助開發(fā)人員以看上去同步的方式使用Promises編寫異步代碼。
But Promises are actually similar to callbacks and have the same nesting problem at some degree.
但是Promises實際上類似于回調(diào),并且在某種程度上具有相同的嵌套問題。
Since developers are always looking for better solutions we now have Observables which use the observer software pattern.
由于開發(fā)人員一直在尋找更好的解決方案,因此我們現(xiàn)在有了使用觀察者軟件模式的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.
觀察者模式是一種軟件設(shè)計模式,其中一個稱為主題的對象會維護(hù)其依賴者的列表(稱為觀察者),并通常通過調(diào)用其方法之一來自動將狀態(tài)更改通知他們。 觀察者模式 。
Observables are implemented in the ReactiveX project which has implementations in various languages. RxJS is the JavaScript implementation.
可觀察對象在ReactiveX項目中實現(xiàn),該項目具有各種語言的實現(xiàn)。 RxJS是JavaScript實現(xiàn)。
Note: Observables are implemented in many other libraries such as zen-observable and xstream but RxJS Observables are the most popular in JavaScript.
注意 :Observables在許多其他庫中實現(xiàn),例如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的內(nèi)置功能,但是建議將其添加到EcmaScript中。
Now, what's an RxJS Observable?
現(xiàn)在,什么是RxJS Observable?
An Observable is an entity that emits (or publishes) multiple data values (stream of data) over time and asynchronously.
一個Observable是一個實體,它隨時間推移并異步地發(fā)出(或發(fā)布)多個數(shù)據(jù)值(數(shù)據(jù)流)。
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.
可觀察表示未來值或事件的可調(diào)用集合的想法。
Observers and Subscriptions
觀察者和訂閱
There are also related concepts that you'll work with when using Observables which are Observers and Subscriptions.
使用Observable( 觀察者和訂閱)時,還需要處理一些相關(guān)概念。
Observers are also called listeners (or consumers) as they can listen or subscribe to get the observed data.
觀察者也稱為偵聽器(或使用者),因為他們可以偵聽或訂閱以獲取觀察到的數(shù)據(jù)。
From the RxJS docs:
從RxJS文檔中:
Observer is a collection of callbacks that knows how to listen to values delivered by the Observable.
Observer是一組回調(diào),它們知道如何偵聽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()方法,您可以調(diào)用這些方法來取消訂閱以從Observable中檢索發(fā)布的值。
From the official docs:
從官方文檔:
Subscription represents the execution of an Observable, is primarily useful for cancelling the execution.
訂閱表示Observable的執(zhí)行,主要用于取消執(zhí)行。
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的一種特殊類型,觀察者也可以訂閱它以接收已發(fā)布的值,但有一個區(qū)別: 值被多播到許多Observers上 。
Note: By default an RxJS Observable is unicast.
注意 :默認(rèn)情況下,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具有獨立的執(zhí)行,而多播則意味著多個觀察者共享Observable的執(zhí)行。
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.
因此,當(dāng)使用Subject而不是普通Observable時,所有訂閱的Observer都將獲得相同的發(fā)射數(shù)據(jù)值。
Note: Subjects are also Observers i.e they can also subscribe to other Observables and listen to published data.
注意 :主題也是觀察者,即他們也可以訂閱其他可觀察對象并收聽發(fā)布的數(shù)據(jù)。
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.
與常規(guī)的Observables不同,Subject被稱為hot 。 一個熱的Observable甚至在任何觀察者訂閱之前就開始發(fā)出事件,這意味著如果觀察者在正確的時間不進(jìn)行訂閱,則觀察者可能會丟失先前發(fā)出的值,而冷的 Observable則在至少一個觀察者被訂閱時才開始發(fā)出值。
Note: You can use the asObservable() method to convert a subject to only an Observable.
注意 :可以使用asObservable()方法將主題轉(zhuǎn)換為僅可觀察的對象。
RxJS的BehaviorSubject和ReplaySubject (RxJS’ BehaviorSubject and ReplaySubject)
RxJS provides two other types of Subjects: BehaviorSubject and ReplaySubject.
RxJS提供了另外兩種類型的主題: BehaviorSubject和ReplaySubject 。
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.
對于普通主題,稍后在某個點訂閱的觀察者將不會接收在訂閱之前發(fā)出的數(shù)據(jù)值。 在許多情況下,這不是我們想要實現(xiàn)的期望行為。 可以使用BehaviorSubject和ReplaySubject解決。
ReplaySubject works by using a buffer that keeps the emitted values and re-emit them when new Observers are subscribed.
ReplaySubject通過使用緩沖區(qū)來工作,該緩沖區(qū)保留發(fā)出的值并在訂閱新的Observer時重新發(fā)射它們。
BehaviorSubject works like ReplaySubject but only re-emits the last emitted value.
BehaviorSubject工作方式類似于ReplaySubject但僅重新發(fā)出最后發(fā)出的值。
如何創(chuàng)建可觀察的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()方法創(chuàng)建RxJS Observable,該方法采用帶有observer參數(shù)的函數(shù)。 然后,您可以訂閱返回的Observable實例。
There many other methods to create Observables besides the static create() method:
除了靜態(tài)create()方法之外,還有許多其他方法可以創(chuàng)建Observables:
The lift() instance method which creates a new Observable from the instance (the source) it's called on,
lift()實例方法,可從調(diào)用該實例的實例(源)創(chuàng)建一個新的Observable,
The of([]) operator which creates an Observable of a single value. We'll see an example next,
of([])運算符,它創(chuàng)建單個值的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,
創(chuàng)建一個Observable的interval(interval)運算符發(fā)出一個無窮大的數(shù)字序列。 每個數(shù)字都會以固定的時間間隔(以秒為單位)發(fā)出,
The timer() operator which returns an Observable that after a specified amount of time, emits numbers in sequence every specified duration,
timer()運算符,它返回一個Observable,在指定的時間量后,它在每個指定的持續(xù)時間內(nèi)依次發(fā)出數(shù)字,
The from() method that creates an Observable from a Promise or an array of values,
from() Promise或值數(shù)組創(chuàng)建Observable的from()方法,
The fromEvent() method that creates an Observable from a DOM event,
從DOM事件創(chuàng)建Observable的fromEvent()方法,
The ajax() method which creates an Observable that sends an Ajax request.
創(chuàng)建一個發(fā)送一個Ajax請求的Observable的ajax()方法。
We'll see these creation methods by example later.
我們將在后面的示例中看到這些創(chuàng)建方法。
如何訂閱可觀察的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.
創(chuàng)建Observable ,可以在實例上使用Subscription subscribe()方法對其進(jìn)行預(yù)訂,該方法返回Subscription的實例。
RxJS可觀察的簡單示例 (A Simple Example of the RxJS Observable)
Let's now see a simple example of creating and working with an Observable.
現(xiàn)在,讓我們看一個創(chuàng)建和使用Observable的簡單示例。
First let's create an Observable:
首先讓我們創(chuàng)建一個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.
我們創(chuàng)建一個ob$ Observable,然后在傳入的方法的主體中定義Observable應(yīng)該執(zhí)行的邏輯。
In this example, the Observable will simply emit the A new value! value to the subscribed Observer.
在此示例中,Observable將僅發(fā)出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.
我們調(diào)用觀察者對象的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可以與它們進(jìn)行通信。
The next() method is used by the Observable to pass values (publish values) to the subscribed Observer.
Observable使用next()方法將值(發(fā)布值)傳遞給訂閱的Observer。
Next, let's create an observer object:
接下來,讓我們創(chuàng)建一個觀察者對象:
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進(jìn)行通知。
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概念的實現(xiàn),但還提供了多種運算符,使您可以編寫Observable。
Operators offer a declarative way to perform complex asynchronous operations with Observables.
運算符提供了一種聲明性的方式來使用Observables執(zhí)行復(fù)雜的異步操作。
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.
操作員通過觀察源的發(fā)射值并對其進(jìn)行預(yù)期的轉(zhuǎn)換來對源Observable進(jìn)行操作,然后返回具有已修改值的新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()等。
管道:結(jié)合多個運算符 (Pipes: Combining Multiple Operators)
RxJS provides two versions of the pipe() function: A standalone function and a method on the Observable interface.
RxJS提供了pipe()函數(shù)的兩個版本:獨立函數(shù)和Observable接口上的方法。
You can use the pipe() function/method to combine multiple Operators. For example:
您可以使用pipe()函數(shù)/方法來組合多個運算符。 例如:
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()方法將根據(jù)1, 2, 3, 4, 5,6數(shù)字創(chuàng)建并返回一個Observable 1, 2, 3, 4, 5,6而pipe()方法將在每個發(fā)射值上應(yīng)用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的內(nèi)置類型,例如:
The HttpClient methods return Observables and actual requests are only sent when you subscribe to the returned Observable.
HttpClient方法返回Observables,只有在您訂閱返回的Observable時才發(fā)送實際請求。
- 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 (包含有關(guān)與路由器出口上當(dāng)前加載的組件關(guān)聯(lián)的路由的信息)也具有許多可觀察的屬性,例如,用于路由參數(shù)的params和paramMap 。
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:
假設(shè)您有一個Angular組件,并且將Router服務(wù)注入為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. 響應(yīng)式表單模塊使用響應(yīng)式編程和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庫實現(xiàn))。 如果您使用的是Angular CLI 6 | 7,則默認(rèn)情況下將在項目上安裝RxJS 6。
Otherwise you can install it via npm using:
否則,您可以使用以下方法通過npm安裝它:
$ npm install rxjs --saveTo be able to use the Observable symbol in your code, you first need to import it:
為了能夠在代碼中使用Observable符號,首先需要將其導(dǎo)入:
import { Observable } from 'rxjs';This is the new import path in RxJS 6 which is different from RxJS 5.
這是RxJS 6中與RxJS 5不同的新導(dǎo)入路徑。
使用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.
默認(rèn)情況下,新的Angular HttpClient與Observables一起使用。 get() , post() , put()和delete()返回Observable接口的實例。
HTTP requests are only sent when we subscribe to the Observable.
僅當(dāng)我們訂閱Observable時才發(fā)送HTTP請求。
This is an example of making an HTTP request:
這是發(fā)出HTTP請求的示例:
getItems(): Observable<Item[]> {return this.httpClient.get<Item[]>(this.itemUrl); }We assume that you have injected the HttpClient service as httpClient.
我們假設(shè)您已將HttpClient服務(wù)注入為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并返回發(fā)出的數(shù)據(jù)。 例如。 假設(shè)我們有這種方法:
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:
在組件上調(diào)用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.
可觀察變量用于更好地支持事件處理,異步編程以及處理多個值。 當(dāng)您定義一個Observable來為使用者發(fā)布一些值時,這些值直到您實際訂閱Observable時才會發(fā)出。
The Consumer that subscribes to the Observable keeps receiving values until the Observable is completed or the consumer unsubscribes from the observable.
訂閱可觀察對象的消費者將繼續(xù)接收值,直到該可觀察對象完成或消費者不再訂閱該可觀察對象。
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()方法。 它使您可以將可觀察到的響應(yīng)映射到其他值。 例如:
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()運算符返回響應(yīng)對象的data屬性。
The operator enables us to map the response of the Observable stream to the data value.
運算符使我們能夠?qū)bservable流的響應(yīng)映射到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包中導(dǎo)入可管道運算符map() ,并使用pipe()方法(采用可變數(shù)量的可管道運算符)包裝該運算符。
使用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.
當(dāng)HTTP響應(yīng)的狀態(tài)碼為200時,我們使用filter()運算符僅向可觀察流的觀察者發(fā)出通知。
結(jié)論 (Conclusion)
In this tutorial, you have been introduced to reactive programming, data streams and RxJS 6.
在本教程中,向您介紹了React式編程,數(shù)據(jù)流和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.
您已經(jīng)了解到,React式編程是關(guān)于使用異步數(shù)據(jù)流進(jìn)行編碼,并且RxJS是實現(xiàn)Observables和觀察者模式的最流行的實現(xiàn)。
You have learned what an Observable is — An object that emits or publishes values over time and asynchronously.
您已經(jīng)了解了什么是Observable-隨時間推移以異步方式發(fā)出或發(fā)布值的對象。
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).
您已經(jīng)了解了與Observables相關(guān)的概念,例如Observers和Subscriptions-Observers是偵聽和使用Observable發(fā)布的值的對象,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之間的區(qū)別。 提醒一下,多播Observable在其所有觀察者之間共享其執(zhí)行。
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在創(chuàng)建值時開始發(fā)布值的時間,甚至在獲得任何訂閱之前。
You learned about RxJS operators which are methods that are used to compose Observables and work on their data streams.
您了解了RxJS運算符,它們是用于構(gòu)成Observable并對其數(shù)據(jù)流進(jìn)行處理的方法。
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在其許多常用模塊(例如HttpClient , Router和ReactiveForms )中使用RxJS v6處理異步操作和API(而不是回調(diào)或Promises)。
This article was originally posted in techiediaries.
本文最初發(fā)表在技術(shù)文章上 。
翻譯自: https://www.freecodecamp.org/news/angular-rxjs-in-depth/
rxjs angular
總結(jié)
以上是生活随笔為你收集整理的rxjs angular_Angular RxJS深度的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 做梦梦到别人掉水里了是什么预兆
- 下一篇: 做梦梦到丧尸什么意思