Application RxJS in angular in

Foreword

RxJS all that was senseless after looking document, until I met a lot of functions to be achieved in the application of the angular RxJS time ... perfect!

What is Observable?

Observable just an ordinary function, to want him to do something, you need to use in conjunction with the observer; the former is the latter is subject to attack. And this observer (we will explain later) with just a simple object next, error, complete only. Finally, we need to start by subscribe Subscribe Observable; otherwise it will not have any reaction; * environment can be understood as street together for them to provide, but also returns a subscription can be used to cancel the operation (called in at RxJS unsubscribe).

When setting Observable observer, connected and get this process the raw data is called producer, may be the click event in the DOM, input events, or a more complex HTTP traffic.

For a better understanding of, start with a simple example to start:

import { Component } from '@angular/core';
import { Observable, Subscription } from 'rxjs';

@Component({
  selector: 'app-home',
  template: `<input type="text"> `
})
export class HomeComponent {
  ngOnInit() {
    const node = document.querySelector('input[type=text]');

    // 第二个参数 input 是事件名,对于input元素有一个 oninput 事件用于接受用户输入
    const input$ = Observable.fromEvent(node, 'input');
    input$.subscribe({
      next: (event: any) => console.log(`You just typed ${event.target.value}!`),
      error: (err) => console.log(`Oops... ${err}`),
      complete: () => console.log(`Complete!`)
    });
  }
}
复制代码

Example Observable.fromEvent () returns a Observable, and listen for an input event, the event is triggered when an Event will be sent to the corresponding Observer observer.

What is the Observer?

observer is very simple, as in the example above is to receive a subscription subscribe observer method.

Angular we subscribe in general will write:

input$.subscribe((event: any) => {
});
复制代码

From the point of view and grammar subscribe({ next, error, complete })is the same.

When Observable produce a new value, it will notify the observer next(), and when the call can fail to capture error().

When Observable subscribed, unless you call the observer complete()or unsubscribe()unsubscribe from two circumstances beyond; will always pass values to the observer.

Observable value produced allowed to pass through a sequence of operations or formatting, a value finally obtained data to a viewer, and all this is a chain operator sequence to complete, each operator will generate a new Observable. And we call this process sequence is: stream.

What is the operator?

As said before, Observable wording can be chained, which means that we can:

Observable.fromEvent(node, 'input')
  .map((event: any) => event.target.value)
  .filter(value => value.length >= 2)
  .subscribe(value => { console.log(value); });
复制代码

The following is the entire sequence of steps:

Assume that the user input: a Observable oninput react to a trigger event, as parameter values ​​passed to the next observer (). map () returns the contents of a new event.target.value Observable, and calls the next () passed to the next observer. filter () if the value of the length> = 2, then, a new Observable is returned, and call next () passed to the next observer. Finally, the result is passed to block subscriptions subscribe. Just remember that every operator will return a new Observable, no matter how many operator, eventually only the last one will be Observable subscription.

Do not forget to unsubscribe.

Why do you need to unsubscribe

Observable when there will be pushed to subscribers when data is generated, so it may be unlimited push data to subscribers. Because of this, creating components inside when the Angular sure to unsubscribe operation to avoid memory leaks, we know know backside is a necessary thing in the world of SPA.

unsubscribe

Talked in the preceding example, call subscribe (), the returns can be used to cancel a Subscription unsubscribe (). The most reasonable way to call it ngOnDestroy.

ngOnDestroy() {
    this.inputSubscription.unsubscribe();
}
复制代码
takeUnit

A very elegant method to unsubscribe

Observable.fromEvent(node, 'input')
  .takeUnit((event: any) => this.show)
  .subscribe(value => { console.log(value); });

ngOnDestory(): void {
    this.show = false;
}
复制代码

Subject

If the observer is Observable attack by combination, then the Subject is a person that is also subject to attack. Because of this, we write a Servicefor data transfer, always use new Subject. An example is shown below:

@Injectable()
export class MessageService {
    private subject = new Subject<any>();

    send(message: any) {
        this.subject.next(message);
    }

    get(): Observable<any> {
        return this.subject.asObservable();
    }
}
复制代码

When the component F components needed to pass data to M, we can use the send () F in the assembly.

constructor(myService: MyService)
ngOnInit() {
    this.myService.send('message');
}
复制代码

M component data receiving:


constructor(myService: MyService)
ngOnInit() {
    this.myService.get.subscribe(data => {
        console.log(data); // message
    })
}
复制代码

EventEmitter

EventEmitter is equivalent to the angular Subject

// my-component.component.ts
@outPut() onChange = new EventEmitter<String>();

onClick() {
    this.onChange.emit('hello world');
}
复制代码
<!-- parent-coponent.component.html -->
<my-component onChange="change($event)"></my-component>
复制代码
// parent-coponent.component.ts
change(value) {
    console.log(value) // hello world
}
复制代码

At last

RxJS have a lot of operators, as detailed in my other article "RxJS (1) common Operators".

Reproduced in: https: //juejin.im/post/5cf0db2f518825332550d16d

Guess you like

Origin blog.csdn.net/weixin_34281477/article/details/91452086