Angular2 使用 Observables From Other Sources

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

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:

+

import {Component} from '@angular/core';
import {Http} from '@angular/http';
import 'rxjs/Rx';

@Component({
    selector: 'app',
    template: `
      Angular HTTP requests using RxJs Observables!
      
  • {{doctor.name}}
`
}) export class MyApp { private doctors = []; constructor(http: Http) { http.get('http://jsonplaceholder.typicode.com/users/') .flatMap((data) => data.json()) .subscribe((data) => { this.doctors.push(data); }); } }

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.

+

import {Component} from '@angular/core';
import {FormControl, FormGroup, FormBuilder} from '@angular/forms';
import 'rxjs/add/operator/map';

@Component({
    selector: 'app',
    template: `
      
You Typed Reversed: {{data}}
`
}) export class MyApp { email: FormControl; coolForm: FormGroup; data: string; constructor(private fb: FormBuilder) { this.email = new FormControl(); this.coolForm = fb.group({ email: this.email }); this.email.valueChanges .map(n=>n.split('').reverse().join('')) .subscribe(value => this.data = value); } }

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.

+

你可能感兴趣的:(Angular2,angular)