angular sse_Angular和服务器发送事件(SSE)

商经业
2023-12-01

angular sse

In this post I will show you how to connect to Server Sent Events (SSE) source in Angular app. We will create a small prototype that will connect to Server Sent Events (SSE) endpoint using Event Source API, resulting in events wrapped into Observable and run inside Angular Zone.

在这篇文章中,我将向您展示如何在Angular应用程序中连接到服务器发送事件 (SSE)源。 我们将创建一个小型原型,该原型将使用事件源API连接到服务器发送事件(SSE)端点,从而将事件包装到Observable中并在Angular Zone中运行。

Server-Sent Events (SSE) is a server push technology enabling a client to receive automatic updates from a server via HTTP connection. The Server-Sent Events EventSource API is standardized as part of HTML5 by the W3C. — Wikipedia

服务器发送事件 ( SSE )是一种 服务器推送 技术,使客户端可以通过HTTP连接从服务器接收自动更新。 W3C 将服务器发送的事件EventSource API标准化为 HTML5 一部分 维基百科

For this tutorial you will need following tools:

对于本教程,您将需要以下工具:

创建干净的Angular项目 (Creating clean Angular project)

First let’s create a clean Angular project. Use the following Angular CLI command from your terminal to do so:

首先让我们创建一个干净的Angular项目。 从终端使用以下Angular CLI命令来执行此操作:

ng new angular-sse

This command creates a clean project and installs all dependencies. Luckily, this project doesn’t require any third party deps — Angular provides everything you need to interact with Server Sent Events (SSE)

此命令将创建一个干净的项目并安装所有依赖项。 幸运的是,该项目不需要任何第三方部门-Angular提供了与服务器发送事件(SSE)进行交互所需的一切

连接到服务器发送事件(SSE)端点 (Connecting to Server Sent Events (SSE) endpoint)

Next, enter the project directory (angular-sse in my case), and create a new service using following terminal command:

接下来,进入项目目录(在我的情况下为angular-sse ),并使用以下终端命令创建新服务:

ng generate service sse

As a result, the SseService is created and wired into the Angular project. Now, lets' write some actual code. The snippet below is the complete code of the SseService class:

结果,创建了SseService并将其连接到Angular项目中。 现在,让我们写一些实际的代码。 下面的代码段是SseService类的完整代码:

import { Injectable, NgZone } from "@angular/core";
import { Observable } from "rxjs";@Injectable({
providedIn: "root"
})
export class SseService {
constructor(private _zone: NgZone) {} getServerSentEvent(url: string): Observable<any> {
return Observable.create(observer => {
const eventSource = this.getEventSource(url); eventSource.onmessage = event => {
this._zone.run(() => {
observer.next(event);
});
}; eventSource.onerror = error => {
this._zone.run(() => {
observer.error(error);
});
};
});
} private getEventSource(url: string): EventSource {
return new EventSource(url);
}
}

Resulting service creates a concise and easy to use interface for interacting with Server Sent Events (SSE). Here, we unify the logic used to connect to any endpoint that supports SSE.

生成的服务创建了一个简洁易用的界面,用于与服务器发送事件(SSE)进行交互。 在这里,我们统一了用于连接到支持SSE的任何端点的逻辑。

In principle, this service connects to SSE endpoint using Event Source API, allowing to box this into Observable object. This Observable is then run inside the Angular Zone. This allows Angular to detect events and execute the underlying logic correctly.

原则上,此服务使用事件源API连接到SSE端点,从而允许将其装箱到Observable对象中。 然后,该ObservableAngular Zone中运行。 这使Angular能够检测事件并正确执行底层逻辑。

订阅可观察 (Subscribing to Observable)

Next, let’s create a component that subscribes to SSE endpoint using the SseService observable. Similarly to creating a service, using Angular CLI for that:

接下来,让我们创建一个使用SseService observable订阅SSE端点的SseService 。 与创建服务类似,为此使用Angular CLI:

ng new component home

Furthermore, I will use this newly created HomeComponent to test the service and connect to testing SSE endpoint. Open the home.component.ts file and insert the following:

此外,我将使用这个新创建的HomeComponent来测试服务并连接到测试SSE端点。 打开home.component.ts文件并插入以下内容:

import { Component, OnInit } from "@angular/core";
import { SseService } from "src/app/services/sse/sse.service";@Component({
selector: "app-home",
templateUrl: "./home.component.html",
styleUrls: ["./home.component.scss"]
})
export class HomeComponent implements OnInit {
constructor(private sseService: SseService) {} ngOnInit() {
this.sseService
.getServerSentEvent("http://localhost:8082/raw")
.subscribe(data => console.log(data));
}
}

The code above, connects to SSE endpoint (http://localhost:8082/raw in my case) using the SseService. After that, the events are logged into the console, for debugging.

上面的代码使用SseService连接到SSE端点(在我的情况下为http:// localhost:8082 / raw )。 之后,将事件记录到控制台中以进行调试。

摘要 (Summary)

In conclusion using Server Sent Events (SSE) in Angular is quite simple and allows for creating cool, reactive applications. I hope you have found this post useful. If so, don’t hesitate to like or share this post. Additionally you can follow me on my social media if you fancy so :)

总之,在Angular中使用服务器发送事件(SSE)非常简单,并允许创建很酷的响应式应用程序。 我希望您发现这篇文章有用。 如果是这样,请随时喜欢或分享此帖子。 此外,如果您愿意,也可以在我的社交媒体上关注我:)

翻译自: https://medium.com/javascript-in-plain-english/angular-and-server-sent-events-sse-54c29b4f174d

angular sse

 类似资料: