Angular Observables和Http

前端之家收集整理的这篇文章主要介绍了Angular Observables和Http前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我很难将我的大脑缠绕在Angular的观察者身上.我来自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);
}
...
如何推理Observables?

Observables处理流.流可以是几乎任何东西,但您可以将它们视为异步事件的抽象数组.这很有用,因为您现在可以更清楚地推理它们:

> abstract因为Observable可以生成任何类型的值:String,Boolean,Object
>数组因为Observable的Operators与JavaScript的数组方法类似:map(),filter(),reduce()
>因为Observable是值的包装器
>异步,因为Observable可能会也可能不会执行
>事件因为需要触发Observable

何时使用Observables?

您通常在需要执行任务或涉及多个步骤的操作时使用Observable.这可以作为您的起点,您可以根据需要简化或增加复杂性.

你应该有一个“计划”,或者至少有一个模糊的想法,那些步骤应该是什么.听起来很明显,但很多问题都出现了,因为你不知道自己想要什么(;

一旦你计划了一个动作(作为一系列步骤),你可以从任何一端开始,但我认为最好从最后开始.至少在你了解更多之前.

I have a component that simply displays a list of messages for a general topic. For now,I have one topic that all messages belong to. If the topic doesn’t exist,then it should be created. The message and topic calls are all done through a REST api.

In a non-async world,I would program it in order. The message service would see if the topic exists. If it doesn’t,then it has the topic service create it. After it has the topic,it then fetches all of the messages within that topic.

对于您的用例计划将是:[“(创建主题)”,“选择主题”,“显示消息”].消息是抽象数组,select和create是异步事件.

如何使用Observable?

正如我上面所说,让我们从最后开始 – “显示消息”.

<div *ngFor="#message of messages"></div>

我们知道我们正在处理Observable.of(消息)(这是你手动创建它的方式).接下来,您需要“填充”消息流,并且可以使用返回Observable的Http服务来执行此操作.由于您从服务器获得的消息被Http服务包含在几个“层”中,因此我们可以利用Observable的功能链接运算符(运算符返回Observable)并获取我们需要的消息:

getMessages(topic) {
    this.http.get("/messages?topic=" + topic)
      .map(response => response.json())
      // chain other operators here...
      .filter(message => !message.private)
  }

你可以使用你需要的任何Operators …这导致了Observables的下一个重大事件:

“热”和“冷”观察者

Observable默认是冷的.这意味着当您创建一个observable时,您只需描述它应该做什么.它不会立即执行这些操作(如Promise一样),它需要被触发.

你可以通过订阅来触发它,或者使用subscribe()方法手动触发它,或者你可以让Angular使用异步管道(它订阅你)来使它变热.

getMessages(topic) {
    this.http.get("/messages?topic=" + topic)
      .map(response => response.json())
      .subscribe(messages => this.messages = messages);
  }

注意变化

接下来要做的事情(或之前我们在计划中倒退)就是“选择主题”.观看所选主题的价值并通过加载新消息来响应它的变化会很高兴.这可以使用Subject完成.

A Subject is a sort of bridge or proxy that is available in some implementations of ReactiveX that acts both as an observer and as an Observable. Because it is an observer,it can subscribe to one or more Observables,and because it is an Observable,it can pass through the items it observes by reemitting them,and it can also emit new items.

我们可以设置主题$来这样做:

class ListComponent {
  public messages;
  public topic$= new Subject();

  constructor(private http: Http) {
    this.getMessages('posts');
    this.topic$
      .subscribe(topic => this.getMessages(topic));
  }

  getMessages(topic: string) {....}

  selectTopic(topic: string) {
    this.topic$.next(topic)
  }
}

包起来

最后一步是“(创建主题)”如果不存在.假设主题不存在,假设服务器将返回错误

getMessages(topic: string) {
    this.http.get(API_URL + topic)
      .map(response => response.json())
      .subscribe(
        messages => this.messages = messages,error => this.createTopic(topic)
      );
  }

  createTopic(topic: string) {
    this.http.post(API_URL + topic,{ body: JSON.stringify(topic) })
      .map(response => response.json())
      .subscribe();
  }

这是这个例子的@L_404_4@.你可以看到它并不难做(50行代码……).您可以轻松移动物品并根据需要创建服务.

原文链接:https://www.f2er.com/angularjs/143729.html

猜你在找的Angularjs相关文章