// check the plnkr for the full list of importsimport {...} from '...';
@Component({selector: 'my-app',template: `<div><h2>Wikipedia Search</h2><input #term type="text" (keyup)="search(term.value)"><ul><li *ngFor="let item of items">\{\{item}}</li></ul></div>`})export class AppComponent {items: Array<string>;
constructor(private wikipediaService: WikipediaService) {}
search(term) {this.wikipediaService.search(term).then(items => this.items = items);}}
export class App {items: Array<string>;term = new FormControl();constructor(private wikipediaService: WikipediaService) {this.term.valueChanges.debounceTime(400) // wait for 400 ms pause in events.distinctUntilChanged() // ignore if next search term is same as previous.subscribe(term => this.wikipediaService.search(term).then(items => this.items = items));}}
var promise = new Promise((resolve, reject) => {// do something once, possibly async// code inside the Promise constructor callback is getting executed synchronously
if (/* everything turned out fine */) {resolve("Stuff worked!");}else {reject(Error("It broke"));}});
//after the promise is resolved or rejected we can call .then or .catch method on it
promise.then((val) => console.log(val)) // logs the resolve argument.catch((val) => console.log(val)); // logs the reject argument
const numberPromise = new Promise((resolve) => {resolve(5);resolve(10);});
numberPromise.then(value => console.log(value));// still prints only 5
可观察:在一段时间内发出多个值
例如:
const numberObservable = new Observable((observer) => {observer.next(5);observer.next(10);});
numberObservable.subscribe(value => console.log(value));// prints 5 and 10