原文: https://codingthesmartway.com/getting-started-with-rxjs-part-1-setting-up-the-development-environment-creating-observables/

----------------------------------------------------------------

Getting Started With RxJS – Part 1: Setting Up The Development Environment & Creating Observables


Subscribe On YouTube

Code

Part 1: Setting Up The Development Environment & Creating Observables
Part 2: Subscriptions
Part 3: Hot And Cold Observables

RxJS (Reactive Extensions for JavaScript) is a library for transforming, composing, and querying streams of data. It brings the concept of reactive programming to the web. The library allows you to work with asynchronous data streams with ease. Asynchronous data streams can be described in the following way:

  • Asynchronous: Callback functions are registered to be invoked when results are available. We’re able to wait for data to become available without blocking the application.
  • Data Streams: Sequences of data made available over time. You don’t need all the information to be present in order to start using them.

In this Getting Started With RxJS tutorial series you’ll be able to get started with the RxJS library, get insights and a profound understanding of the most important concepts and building blocks.

In this first part of this series we’re going to set up the development environment and get started with the concept of Observables.

Observables are just a representation of any set of values over any amount of time. This is the most basic building block of RxJS.

RxJS is part of the ReactiveX project. The project’s website can be found at http://reactivex.io/:

Let’s get started by building a sample project and learn how Observables can be used in practice.


If you like CodingTheSmartWay, then consider supporting us via Patreon. With your help we’re able to release developer tutorial more often. Thanks a lot!


Installing Dependencies

To get started with our demo project we first need to create a new project folder:

$ mkdir rxjs-test

Next, change into that newly created folder by executing:

$ cd rxjs-test

Now we’re using NPM (Node.js Package Manager) to create a new package.json file inside of our project folder:

$ npm init -y

If you haven’t installed Node.js (and NPM) already on your system you first need to go to https://nodejs.org/first and follow the steps which are needed to install Node.js and NPM for your specific platform.

Next we need to add and install a few dependencies by using NPM again in the following way:

$ npm install rxjs webpack webpack-dev-server typescript ts-loader

Here we’re installing Webpack, TypeScript, the corresponding TypeScript loader for Webpack, and the Webpack development web server.

Webpack is a module bundler for modern JavaScript applications. When Webpack processes your application, it internally builds a dependency graph which maps every module your project needs and generates one or more bundles.

TypeScript is an open-source programming language developed and maintained by Microsoft. It is a strict syntactical superset of JavaScript, and adds optional static typing to the language.

We also need to make sure that the Webpack CLI (Command Line Interface) is being installed as a development dependencies:

$ npm install webpack-cli --save-dev

Adding Script To Package.JSON

Let’s add a script with name start to the scripts section in package.json:

  "scripts": {
"start": "webpack-dev-server --mode development"
},

This script is executing the webpack-dev-server command in development mode to start up the Webpack development web server. Later on we’re able to execute the script by using the NPM command in the following way:

$ npm run start

Setting Up Webpack

Next, let’s add the Webpack configuration to our project. Therefore create a new file webpack.config.js in the root project folder and insert the following configuration code:

const path = require('path');

module.exports = {
entry: './src/index.ts',
devtool: 'inline-source-map',
module: {
rules: [
{
test: /\.tsx?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: [ '.tsx', '.ts', '.js' ]
},
output: {
filename: 'bundle.js',
path: path.resolve(__dirname, 'dist')
}
};

Configuring TypeScript

Furthermore we need to include the TypeScript compiler configuration in the project as well. To do so create a new file tsconfig.json and insert the following JSON code which contains configuration properties for the TypeScript compiler:

{
"compilerOptions": {
"outDir": "./dist/",
"sourceMap": true,
"noImplicitAny": true,
"module": "es6",
"moduleResolution": "node",
"target": "es6",
"allowJs": true,
"lib": [
"es2017",
"dom"
]
}
}

Creating An Index.html File

Next, let’s create the index.html file inside of our project folder:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>RxJS Demo</title> <style>
body { font-family: 'Arial'; background: lightgray }
ul { list-style-type: none; padding: 20px; }
li { padding: 15px; background: lightcoral; margin-bottom: 10px; }
</style>
</head>
<body>
<h1>RxJS Demo</h1>
<div>
<ul id="list"></ul>
</div>
<script src="/bundle.js"></script>
</body>
</html>

A few things to note here:

  • The body section of this HTML documents contains a <ul> element with ID list. This element will be used to output information about the Observable to the user.
  • The file bundle.js (which is the output of the Webpack build process) is included via <script> tag at the end of the body section.

Add The TypeScript Code

Now that the project setup is ready, the TypeScript and Webpack configuration is in place, and the HTML document has been created, we’re able to focus on the TypeScript code next.

Insider the project folder create a new subfolder src. Insert that newly created folder create a new file index.ts and insert the following code:

import { Observable } from 'rxjs';

var observable = Observable.create((observer:any) => {
observer.next('Hello World!');
observer.next('Hello Again!');
observer.complete();
observer.next('Bye');
}) observable.subscribe(
(x:any) => logItem(x),
(error: any) => logItem ('Error: ' + error),
() => logItem('Completed')
); function logItem(val:any) {
var node = document.createElement("li");
var textnode = document.createTextNode(val);
node.appendChild(textnode);
document.getElementById("list").appendChild(node);
}

First of all we’re importing Observable from the rxjs library. By using method Observable.create we’re creating an instance of Observable and storing it in observable.

As an argument we’re passing in a callback method which gives us access to an Observer object. Now we’re able to use the Observer methods nextcomplete and error to create notifications of the corresponding types. In this example we’re calling the next method two times to send out notifications with string values. Then the complete method is called to send out the complete notification. After having send out the complete notification we’re calling the next method once again. The expectation here is that no new notification will be raised because the Observable is already completed.

The register callback methods which are invoked if a notification of a certain type is raised are registered by calling the subscribe method of the Observable. We’re able to register up to three callback methods for notification types next, error and complete.

Inside the callback methods we’re making use of a custom helper method logItem. This methods is updating the output by adding new list items to the list element.

Now we’re ready to start of the development web server by using the following command:

$ npm run start

The web application should now be accessible via URL http://localhost:8080 and you should be able to see the following result in the browser:

As expected the output contains three items:

  • Two items printing out the message from the first two next notification
  • One item outputting the complete notification

The last next notification (raised after the Observable was completed) is not emitted and therefore not contained in the output.

What’s Next

Now that you have a first understanding of RxJS Observables we’re going to dive deeper in the upcoming second part of this series and take a closer look at Observables and Subscriptions.

rxjs 入门--环境配置的更多相关文章

  1. Extjs入门——环境配置

    Extjs框架作为一个07年就上线的框架,虽然与现在的框架对比,显得十分臃肿.但是在针对企业内部引用系统上,它依旧能发挥出不错的效果.现在我接触到了Extjs,所以我准备写一个入门框架,简单的介绍Ex ...

  2. cocos2dx 入门 环境配置

    本人立志走游戏开发这条路,很早之前就准备学习cocos2dx,今天终于忙里偷闲入了一下门,把环境配置好了,创建了自己的第一个cocos项目! 一.环境配置 1.下载cocos https://coco ...

  3. go入门环境配置

    1.安装golang(64位).MinGW(64位).LiteIDE(32位) 下载golang安装包,双击安装,默认安装目录:C:\Go: MinGW安装包(x86_64-4.8.2-release ...

  4. Intel Edison学习笔记(二)—— 入门环境配置

    一.安装Screen sudo apt-get install screen 二.配置 1.连接USB,等待出现 2.测试串口是否存在: ls /dev/ttyUSB0 输出/dev/ttyUSB0, ...

  5. MongoDB学习笔记(二:入门环境配置及与关系型数据库区别总结)

    一.下载及安装MongoDB MongoDB下载官网链接:http://www.mongodb.org/downloads 具体安装步骤教程:http://www.shouce.ren/api/vie ...

  6. Spring Security Web应用入门环境搭建

    在使用Spring Security配置Web应用之前,首先要准备一个基于Maven的Spring框架创建的Web应用(Spring MVC不是必须的),本文的内容都是基于这个前提下的. pom.xm ...

  7. 2013 duilib入门简明教程 -- VS环境配置(2)

        既然是入门教程,那当然得基础点,因为搜索duilib相关资料时,发现有些小伙伴到处都是编译错误,以及路径配置错误等等,还有人不知道SVN,然后一个个文件手动下载的.     其实吧,duili ...

  8. 【OpenCV入门教程之一】 安装OpenCV:OpenCV 3.0 +VS 2013 开发环境配置

    图片太多,具体过程参照: [OpenCV入门教程之一] 安装OpenCV:OpenCV 3.0.OpenCV 2.4.8.OpenCV 2.4.9 +VS 开发环境配置 说下我这边的设置: 选择deb ...

  9. Kinect for Windows SDK开发入门(一):开发环境配置

    [译]Kinect for Windows SDK开发入门(一):开发环境配置 前几天无意中看到微软发布了Kinect for windows sensor,进去看了一下Kinect应用的例子,发现K ...

随机推荐

  1. 【Linux开发】【CUDA开发】Ubuntu上安装NVIDIA显卡驱动

    机型为戴尔Vostro3900  显卡型号为GTX 745  对于Nvidia显卡的驱动,如今很多Linux发行版会默认使用名为nouveau的驱动程序.Nouveau是由第三方为Nvidia开发的一 ...

  2. php_mvc实现步骤九(登录验证码,退出-登录标记)

    shop34-17-登录验证码 验证码的分析 登录:防止暴力破解 论坛:防止灌水水 展示类:被抓取. 需要技术: 图片处理技术. 会话session技术. PHP图片处理技术 – GD 具体操作步骤 ...

  3. GAN代码实战

    batch normalization 1.BN算法,一般用在全连接或卷积神经网络中.可以增强整个神经网络的识别准确率以及增强模型训练过程中的收敛能力2.对于两套权重参数,例如(w1:0.01,w2: ...

  4. 【python小记】访问mysql数据库

    题记: 最近因为工作需要,学习了python,瞬间对这个轻松快捷的语给吸引了,以前只知道js脚本是写网页的,没有想到python这个脚本语言的应用范围可以这么广泛,现在做一些简单或稍微复杂的操作,基本 ...

  5. learning、trying、teaching

    在工作中学习和提升,学以致用,学习的效果是最好的:工作后学习不需要大段时间,而是要挤出时间,利用时间碎片来学习. 1,Learning 这是第一阶段,看书.google.看视频.看别人的博客,但要是“ ...

  6. Altium Designer 复制报错-奇怪的问题解决办法

    之前AD画原理图复制元件正常使用,今天使用时复制弹出了错误.很是诧异! 各种搜索查找问题,发现或许是因为前一段时间把,电脑上的所有打印机都删除了导致的. 就安装了一个打印机. 再复制,就不报错了. 或 ...

  7. 【LEETCODE】53、数组分类,简单级别,题目:989、674、1018、724、840、747

    真的感觉有点难... 这还是简单级别... 我也是醉了 package y2019.Algorithm.array; import java.math.BigDecimal; import java. ...

  8. 【LEETCODE】39、第561题 Array Partition I

    package y2019.Algorithm.array; /** * @ProjectName: cutter-point * @Package: y2019.Algorithm.array * ...

  9. Java多线程编程之读写锁【ReentrantReadWriteLock】

    有时候我们需要有这样的需求:        对于同一个文件进行读和写操作,普通的锁是互斥的,这样读的时候会加锁,只能单线程的读,我们希望多线程的进行读操作,并且读的时候不能进行写操作,写的时候不能进行 ...

  10. Unity项目 - 坦克大战3D TankBattle

    目录 游戏原型 项目演示 绘图资源 代码实现 技术探讨 参考来源 游戏原型 游戏玩法:在有界的战场上,玩家将驾驶坦克,代表绿色阵营,与你的队友一起击溃红蓝阵营的敌人,在这场三方大战中夺得胜利! 操作指 ...