<div class="demo"> <section class="m-auto theme-light"> <button class="btn btn-primary" (click)="newObservable()">newObservable</button> <button class="btn btn-info" (click)="concat()">concat</button> <button class="btn btn-secondary" (click)="cancelObservable()">cancelObservable</button> </section> </div>
import { Component } from '@angular/core'; import { map, Observable, interval, from, concat, filter, reduce, scan, tap } from 'rxjs' // const sub = interval(2000).subscribe(res => { // console.log('interval', res); // }); @Component({ selector: 'app-example', templateUrl: './example.component.html', styleUrls: ['./example.component.less'] }) export class ExampleComponent { show: boolean = true constructor() { } newObservable() { // Observable负责从数据源中推送数据(推流),类似Promise // const o = new Observable(subscriber => { // console.log('initial a newObservable'); // subscriber.next(['a', 'b', 'c']);//相当于promise的resolve // }).pipe( // map(res => { // console.log('第一个map'); // return res; // }), // map(res => { // console.log('第2个map'); // return res; // }) // ); // 不订阅,pipe中的所有函数都不会触发 //Observable变量要以$结尾,规范而已. // 不订阅(调用subscribe),pipe中的所有函数都不会触发 const observable$ = new Observable(subscriber => { console.log('aaa'); subscriber.next(1) subscriber.next(2) subscriber.next(3)//相当于promise的resolve setTimeout(() => { subscriber.next(300); // happens asynchronously subscriber.complete()// // 不调用complete方法,下面的observable.subscribe就不会输出complete // 推送结束时触发(即使出现error),不会收到任何值 subscriber.next(300); subscriber.error('error'); }, 1000); }) console.log('before'); //订阅observable$后会执行。相当于promise的then。 // Observable相当于推流。observable$相当于Observer(拉流)。下面是完整写法 observable$.subscribe({ next(value) { console.log('value', value); }, error(error) { console.log(error); }, complete() { console.log('complete'); } }) console.log('after'); } //手动取消 cancelObservable() { // sub.unsubscribe() } concat() { //Observable变量要以$结尾,规范而已. const arr1$ = from([1, 8, 9]) const arr2$ = from([6, 2, 3]) concat(arr1$, arr2$) .pipe( filter(item => item > 2),//返回大于2的数 // scan((s,v)=>s+v,0)//必须要和num类型相加。返回每一次计算结果 reduce((s, v) => s + v, 0),//必须要和num类型相加。返回计算最后的结果 tap(item => { //用于调试 console.log(item); }) ) .subscribe(res => { console.log(res); }) } }
取消订阅
observable.subscribe返回一个Subscription对象
const subscription = observable.subscribe(x => console.log(x)); // 调用subscription.unsubscribe()即可取消订阅 const observable = interval(1000); const subscription = observable.subscribe(x => console.log(x)); setTimeout(() => { subscription.unsubscribe(); }, 5000);
标签:observable,console,log,Observer,res,subscriber,const From: https://www.cnblogs.com/zhaohui9527/p/17207326.html