2017-07-18 17 views
2

我真的很想完全和简单地了解Angular中的Observable和Promises。感谢任何人通过一个简单的例子来给我打电话。Observable和Promise在Angular 4中的一个简单定义

+2

这是一个非常广泛的问题,你可以让你的问题更具体吗? –

+1

Observable和Promises不是特定的。此外,可能重复此https://stackoverflow.com/questions/37364973/angular-promise-vs-observable/37365955#37365955 – brijmcq

回答

2

你可以看一下从@Gunter这个答案,他解释了它在一个非常简单的方式

https://stackoverflow.com/a/37365955/2708210

我想补充一个示例代码为两个

可观察

getLukeSkywalkerObservable(){ 
    return this.http.get('http://swapi.co/api/people/1/') 
     .map(res => { 
     return res.json(); // using maps to filter data returned form the http call 
     }).map(data => { 
     return data; // using maps of maps to filter data returned form the map 
     }).flatMap((jedi) => this.http.get(jedi.homeworld)) 
     .map(res => { 
     return res.json().name; // using flat maps to combine data returned from two observables into one 
     }).catch((error:any) => Observable.throw(error.json().error || 'Server error')); 
    } 

承诺

getLukeSkywalkerPromise(){ 
    return this.http.get('http://swapi.co/api/people/1/').toPromise() 
     .then((data) => { 
     console.log(data); // binding the result from the promise 
     return data.json(); 
     }).then((data) => { 
     console.log(data.name); // more like map of map but limited functionality 
     return data.name; 
     }).catch((ex) => { 
      console.error('Server Error'+ex); 
     }) 
    } 
2

建议阅读http上的角度文档link这个答案来自文档。

Angular http.get返回一个RxJS Observable(你不需要Observable对HTTP请求,因为它是1请求和1响应) Observable是可以用类似数组的操作符处理的事件流。 转换为承诺通常是一个不错的选择。您通常要求http.get()获取单个数据块。当你收到数据,你就完成了。调用组件可以很容易地以Promise的形式消费单个结果。

下面是一个简单的例子: ... /应用/ http.service.ts

import { Injectable } from '@angular/core'; 
import { Http } from '@angular/http'; 
@Injectable() 
export class HttpService { 

constructor(private _http: Http) { } 
retrieveTasks() { 
    return this._http.get('/tasks').map(data=>data.json()).toPromise() 
    } 
} 

注意,_http.get()具有2个功能链接到它,.map.toPromise().map方法用于将返回的对象从HTTP请求转换为json格式的对象,并且使用.toPromise方法强制_http.get()调用将Promise而不是Observable返回给我们。无需在基​​本的HTTP请求中使用Observable的好处,使用Promise使其更加简洁和简单。

相关问题