这是一张值一千字的图表:
Single | Function | Promise
---------|-----------|----------------
Multiple | Iterator | Observable
---------|-----------|----------------
| Sync | Async
| (Pull) | (Push)
Pull - 消费者决定何时发送来自生产者的数据
推送 - 生产者决定何时将数据发送给消费者
将 Observable 视为时事通讯。 订阅简报一次就足够了,只要有新内容可用,您就会继续接收通知 - Observable 在一段时间内发出多个值。
const newsletterProducer = new Subject();
const newsletter$ = newsletterProducer.asObservable();
// It is enough to subscribe only once
newsletter$.subscribe(console.log);
newsletterProducer.next('JS article of the week #1');
// After some time...
timer(1000)
.subscribe(() => newsletterProducer.next('JS article of the week #2'))
在您的 Angular 应用程序中,消费者可能是您的智能组件。他们将订阅可在数据服务中找到的可观察对象。
另一方面,在处理 promises 时,您必须在每次想要接收内容时明确地请求内容 - Promise 发出单个值 .
const getMovies = genre => new Promise(resolve => setTimeout(resolve, 1000, genre + Math.random()));
const actionMoviesPromise = getMovies('action');
actionMoviesPromise.then(m => console.log('#1 ' + m)); // #1 action0.35095072611888156
actionMoviesPromise.then(m => console.log('#2 ' + m)); // #2 action0.35095072611888156
actionMoviesPromise.then(m => console.log('#3 ' + m)); // #3 action0.35095072611888156
const horrorMoviesPromise = getMovies('horror');
horrorMoviesPromise.then(m => console.log('#1 ' + m)); // #1 horror0.7990946657868658
horrorMoviesPromise.then(m => console.log('#2 ' + m)); // #2 horror0.7990946657868658
horrorMoviesPromise.then(m => console.log('#3 ' + m)); // #3 horror0.7990946657868658
如您所见,如果您想获得另一种类型的电影,您必须为此创建另一个承诺并手动致电then。相反,当使用 Observables 时,consumer 所要做的就是 subscribe 到 producer。然后,每当生产者发出新数据时,消费者都会简单地接收它。