【发布时间】:2016-02-17 23:45:22
【问题描述】:
我很难将我的大脑围绕在 Angular 中的 observables 上。我来自 PHP 的世界,那里的东西绝对不是异步的。
我有一个组件,它只显示一般主题的消息列表。现在,我有一个所有消息都属于的主题。如果主题不存在,则应该创建它。消息和主题调用都是通过 REST api 完成的。
在非异步世界中,我会按顺序对其进行编程。消息服务将查看主题是否存在。如果没有,则由主题服务创建它。获得主题后,它会获取该主题中的所有消息。
我知道您订阅了 observable,但是当需要按顺序发生一系列事情时会发生什么? angular 2 http documentation 提供了一个非常简单的示例,即在拨打电话时更新英雄列表。
组件
export class NotificationListComponent implements OnInit {
constructor(private _notificationService:NotificationService) {
}
***
ngOnInit() {
this.getNotifications();
}
getNotifications() {
this._notificationService.getNotifications()
.subscribe(
notifications => this.notifications = notifications,
error => this.errorMessage = <any>error);
}
通知服务
...
getNotifications() {
// call the topic service here for general topic??
return this.http.get('/messages?order[datesent]=DESC')
.map((res) => {
return res.json()["hydra:member"];
})
.map((notifications:Array<any>) => {
let result:Array<Notification> = [];
notifications.forEach((jsonNotification) => {
var Notification:Notification = {
message: jsonNotification.message,
topic: jsonNotification.topic,
datesent: new Date(jsonNotification.datesent),
};
result.push(Notification);
});
return result;
})
.catch(this.handleError);
}
...
主题服务
...
getGeneralTopic() {
var generalTopic;
this.http.get('/topics?name=general')
.map((res) => {
return res.json()["hydra:member"][0];
})
.do(data => console.log(data))
.subscribe(generalTopic => res);
}
...
【问题讨论】:
-
当你说需要发生“一组严格的事情”时,你的意思是 - 按顺序?还是可以乱七八糟的,事情都做完了才去做更重要?
-
我的意思是一系列的事情需要按顺序发生。我的措辞令人困惑
-
在您发布代码并更改标题之前,我就开始写我的答案(:。希望这就足够了,您可以自己更新代码...
标签: angular observable