更新:2016 年 9 月 24 日 Angular 2.0 稳定版
这个问题仍然有很多流量,所以我想更新它。由于 Alpha、Beta 和 7 个 RC 候选者的疯狂变化,我停止更新我的 SO 答案,直到它们稳定为止。
这是使用Subjects 和ReplaySubjects 的完美案例
我个人更喜欢使用ReplaySubject(1),因为它允许在新订阅者附加时传递最后存储的值,即使迟到:
let project = new ReplaySubject(1);
//subscribe
project.subscribe(result => console.log('Subscription Streaming:', result));
http.get('path/to/whatever/projects/1234').subscribe(result => {
//push onto subject
project.next(result));
//add delayed subscription AFTER loaded
setTimeout(()=> project.subscribe(result => console.log('Delayed Stream:', result)), 3000);
});
//Output
//Subscription Streaming: 1234
//*After load and delay*
//Delayed Stream: 1234
因此,即使我延迟连接或需要稍后加载,我也总能得到最新的呼叫,而不必担心错过回调。
这也让您可以使用相同的流向下推送:
project.next(5678);
//output
//Subscription Streaming: 5678
但是,如果您 100% 确定您只需要调用一次呢?保留开放的主题和可观察对象并不好,但总有“如果?”
这就是AsyncSubject 的用武之地。
let project = new AsyncSubject();
//subscribe
project.subscribe(result => console.log('Subscription Streaming:', result),
err => console.log(err),
() => console.log('Completed'));
http.get('path/to/whatever/projects/1234').subscribe(result => {
//push onto subject and complete
project.next(result));
project.complete();
//add a subscription even though completed
setTimeout(() => project.subscribe(project => console.log('Delayed Sub:', project)), 2000);
});
//Output
//Subscription Streaming: 1234
//Completed
//*After delay and completed*
//Delayed Sub: 1234
太棒了!即使我们关闭了主题,它仍然回复了它加载的最后一个内容。
另一件事是我们如何订阅该 http 调用并处理响应。 Map 非常适合处理回复。
public call = http.get(whatever).map(res => res.json())
但是如果我们需要嵌套这些调用怎么办?是的,您可以使用具有特殊功能的主题:
getThing() {
resultSubject = new ReplaySubject(1);
http.get('path').subscribe(result1 => {
http.get('other/path/' + result1).get.subscribe(response2 => {
http.get('another/' + response2).subscribe(res3 => resultSubject.next(res3))
})
})
return resultSubject;
}
var myThing = getThing();
但这太多了,这意味着您需要一个函数来完成它。输入FlatMap:
var myThing = http.get('path').flatMap(result1 =>
http.get('other/' + result1).flatMap(response2 =>
http.get('another/' + response2)));
太好了,var 是一个从最终 http 调用中获取数据的 observable。
好的,但我想要 angular2 服务!
我找到你了:
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { ReplaySubject } from 'rxjs';
@Injectable()
export class ProjectService {
public activeProject:ReplaySubject<any> = new ReplaySubject(1);
constructor(private http: Http) {}
//load the project
public load(projectId) {
console.log('Loading Project:' + projectId, Date.now());
this.http.get('/projects/' + projectId).subscribe(res => this.activeProject.next(res));
return this.activeProject;
}
}
//component
@Component({
selector: 'nav',
template: `<div>{{project?.name}}<a (click)="load('1234')">Load 1234</a></div>`
})
export class navComponent implements OnInit {
public project:any;
constructor(private projectService:ProjectService) {}
ngOnInit() {
this.projectService.activeProject.subscribe(active => this.project = active);
}
public load(projectId:string) {
this.projectService.load(projectId);
}
}
我是观察者和可观察者的忠实粉丝,所以我希望这次更新能有所帮助!
原答案
我认为这是使用Observable Subject 或Angular2 EventEmitter 的用例。
在您的服务中,您创建一个EventEmitter,允许您将值推送到它上面。在 Alpha 45 中,您必须将其转换为 toRx(),但我知道他们正在努力摆脱这种情况,因此在 Alpha 46 中您可以简单地返回EvenEmitter。
class EventService {
_emitter: EventEmitter = new EventEmitter();
rxEmitter: any;
constructor() {
this.rxEmitter = this._emitter.toRx();
}
doSomething(data){
this.rxEmitter.next(data);
}
}
这种方式有一个EventEmitter,您的不同服务功能现在可以推送到它上面。
如果你想直接从调用中返回一个 observable,你可以这样做:
myHttpCall(path) {
return Observable.create(observer => {
http.get(path).map(res => res.json()).subscribe((result) => {
//do something with result.
var newResultArray = mySpecialArrayFunction(result);
observer.next(newResultArray);
//call complete if you want to close this stream (like a promise)
observer.complete();
});
});
}
这将允许您在组件中执行此操作:
peopleService.myHttpCall('path').subscribe(people => this.people = people);
并弄乱您服务中调用的结果。
我喜欢自己创建 EventEmitter 流,以防我需要从其他组件访问它,但我可以看到两种方式都在工作......
这是一个显示带有事件发射器的基本服务的 plunker:Plunkr