Using Observables From Other Sources

In the example above we created Observables from scratch which is especially useful in understanding the anatomy of an Observable.

However, we will often create Observables from callbacks, promises, events, collections or using many of the operators available on the API.

Observable HTTP Events

A common operation in any web application is getting or posting data to a server. Angular applications do this with the Http library, which previously used Promises to operate in an asynchronous manner. The updated Http library now incorporates Observables for triggering events and getting new data. Let's take a quick look at this:

  1. import {Component} from '@angular/core';
  2. import {Http} from '@angular/http';
  3. import 'rxjs/Rx';
  4. @Component({
  5. selector: 'app',
  6. template: `
  7. <b>Angular HTTP requests using RxJs Observables!</b>
  8. <ul>
  9. <li *ngFor="let doctor of doctors">{{doctor.name}}</li>
  10. </ul>
  11. `
  12. })
  13. export class MyApp {
  14. private doctors = [];
  15. constructor(http: Http) {
  16. http.get('http://jsonplaceholder.typicode.com/users/')
  17. .flatMap((data) => data.json())
  18. .subscribe((data) => {
  19. this.doctors.push(data);
  20. });
  21. }
  22. }

View Example

This basic example outlines how the Http library's common routines like get, post, put and delete all return Observables that allow us to asynchronously process any resulting data.

Observable Form Events

Let's take a look at how Observables are used in Angular forms. Each field in a form is treated as an Observable that we can subscribe to and listen for any changes made to the value of the input field.

  1. import {Component} from '@angular/core';
  2. import {FormControl, FormGroup, FormBuilder} from '@angular/forms';
  3. import 'rxjs/add/operator/map';
  4. @Component({
  5. selector: 'app',
  6. template: `
  7. <form [formGroup]="coolForm">
  8. <input formControlName="email">
  9. </form>
  10. <div>
  11. <b>You Typed Reversed:</b> {{data}}
  12. </div>
  13. `
  14. })
  15. export class MyApp {
  16. email: FormControl;
  17. coolForm: FormGroup;
  18. data: string;
  19. constructor(private fb: FormBuilder) {
  20. this.email = new FormControl();
  21. this.coolForm = fb.group({
  22. email: this.email
  23. });
  24. this.email.valueChanges
  25. .map(n=>n.split('').reverse().join(''))
  26. .subscribe(value => this.data = value);
  27. }
  28. }

View Example

Here we have created a new form by initializing a new FormControl field and grouped it into a FormGroup tied to the coolForm HTML form. The Control field has a property .valueChanges that returns an Observable that we can subscribe to. Now whenever a user types something into the field we'll get it immediately.

原文: https://angular-2-training-book.rangle.io/handout/observables/using_observables_from_other_sources.html