Angular is capable of receiving Server-Sent Events (SSE

I'm having trouble getting my component to receive data from the backend server using sse (server side events).

When I access the api endpoint directly, I see that messages are being received over time as expected. However, when I try to call it using Angular, it doesn't seem to work properly.

The backend indicates that the endpoint was called in both cases.

Here is the backend code written in Flask:

@bp.route('/stream')
def stream_text():
    def generate_text():
        # Generate the text in sections
        sections = ['Section 1', 'Section 2', 'Section 3', 'Section 4']
        for section in sections:
            yield section + '\n'
            time.sleep(0.5)

    return Response(generate_text(), mimetype='text/event-stream')

And here is the frontend code written in Angular:

let eventSource: EventSource = new EventSource('/api/chat/stream');  // The URL is correct
eventSource.onmessage = (ev: MessageEvent) => {
   console.log(ev.data)  // This does not display any data
}

I am trying to configure Angular to receive sse data gradually over time rather than all at once.

Answer №1

It is recommended to utilize NgZone when working with EventSource in Angular, as the message events occur outside of the Angular context.

import { NgZone } from "@angular/core";

// ...
constructor(private zone: NgZone) {}

// ...
let eventSource: EventSource = new EventSource('/api/chat/stream'); 
eventSource.onmessage = (ev: MessageEvent) => {
  this.zone.run(() => console.log('EVENT:', ev);
  // Handle the event accordingly
  /*
  this._zone.run(() => {
    this.myObservet.next(ev.data);
    this.store.dispatch(SomeActions.sseEvent({ data: ev.data })
  });
  */
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Custom Cypress command that provides function outputs

When I implement the following code snippet: export const test = () => ({ yo: () => console.log('test'), }); Cypress.Commands.add('test', test); declare global { namespace Cypress { interface Chainable<Subject> { ...

Having trouble making axios a global instance in my Vue project

Previously, I used to import axios in each Vue component separately when making HTTP requests. An example of this can be seen below: <script lang="ts"> import axios from 'axios'; @Component export default class ExamplePage extend ...

Unused Angular conditional provider found in final production bundle

Looking for a way to dynamically replace a service with a mock service based on an environment variable? I've been using the ?-operator in the provider section of my module like this: @NgModule({ imports: [ ... ], providers: [ ... en ...

What is the process for removing a cookie in the MEAN stack?

I am facing an issue with deleting a cookie from my Node API in my Angular client (MEAN stack). On the Node side, I have a controller and a router set up, while on Angular, I subscribe to the service. // node router authRouter.get('/logout', t ...

What is the solution for resolving module issues when working with `unplugin-vue-components`?

I'm currently working on integrating unplugin-vue-components into my project to streamline the process of registering first-party plugin components across all my individual projects. However, I'm encountering difficulties in getting Vite to prope ...

Exploring Typescript Syntax within Apollo Server

When working with Apollo Server, you have the ability to define the server's schema by passing a string into gql. const typeDefs = gql` type Query { getBtcRates: [BtcRate] } `' However, it raises the question - what exactly is gql? Is it a fu ...

Separate configurations for Webpack (Client and Server) to run an Express app without serving HTML files

I am currently developing an application with a Node Backend and I am trying to bundle it with Webpack. Initially, I had a single Webpack configuration with target: node. However, I encountered issues compiling Websockets into the frontend bundle unless I ...

How might I structure a server reply to appear distinct?

My server query can receive two types of responses: interface Response { [id: string]: Data } or interface Response { error: string } However, I am encountering an error message that says: Property 'error' of type 'string' is no ...

Steps to create a formGroup in Angular 12

import { Component, OnInit } from '@angular/core'; import { FormBuilder, FormControl, FormGroup, Validators } from '@angular/forms'; @Component({ selector: 'app-signup', templateUrl: './signup.component.html', ...

Encountering the issue: "Error: The mat-form-field must include a MatFormField

Working on an Angular form, attempting to validate a reactive form with Material design template. Encountering an error when trying to use ngIf condition for validation in the textbox: Error: ERROR Error: mat-form-field must contain a MatFormFieldContr ...

Discovering the url fragments (anchor parameters) using redirectTo in Angular routing

I am currently exploring Angular routing redirection using router tables and wondering if there is a straightforward way to include URL fragments in the redirect. My code snippet looks like this: { path: ':word', redirectTo: 'blah/:wor ...

Utilize Angular with fast.com API

Just starting out with angular and working on a speedtest website as a fun side project. I decided to incorporate the fast.com API into my development. Here's a snippet from my component.ts file: constructor() { const FastSpeedtest = require(&apos ...

Is it still necessary to include /// reference path=" in TypeScript 2.0?

Do you still need to use /// reference path="" in TypeSctipt 2.0, like this: ///<reference path="../../../../typings/app.d.ts"/> or does TS now search all directories specified in tsconfig? I would appreciate a detailed answer... Thanks, Sean ...

Is there a way to create a list of languages spoken using Angular?

I am in search of a solution to create a <select> that contains all the language names from around the world. The challenge is, I need this list to be available in multiple languages as well. Currently, I am working with Angular 8 and ngx-translate, ...

Tips for transferring the "close" function from a modal template to the HTML of another component in Angular 5

Recently, I started learning angular 4 and I need some assistance with a specific issue. I have a component that contains a modal template. Component :- import {Component} from '@angular/core'; import {NgbModal, ModalDismissReasons} from &apos ...

What is the best way to combine a Signal containing an array of Signals in Angular using the merge(/mergeAll) operator?

When working in the world of rxjs, you have the ability to combine multiple Observables using the merge operator. If you have an array of Observables, all you need to do is spread that array into the merge operator like this: merge(...arrayOfObservables). ...

Troubleshooting the issue with the React Storybook Checkbox change handler functionality

I decided to create a checkbox component using React, Typescript, Storybook, and Styled-Components by following this informative tutorial: building-a-checkbox-component-with-react-and-styled-components. I had to make some adjustments to the code because I ...

Utilizing Cordova Plugins in Angular 2 Mobile Apps: A Guide

Spent hours searching with no luck on how to integrate a Cordova plugin into my Angular2 app. Can anyone offer guidance on how to do this successfully? And once the plugin is included, how can I access its methods? ...

When RxJS returns an empty observable, it does not trigger the successful action

I am working with a Rxjs effect that has the following structure: callApiPostSyncPushEffect$ = createEffect(() => { return this.actions$ .pipe( ofType(SyncActions.callApiPostSyncPushPullAction), mergeMap((action) ...

Properties undefined

All of my functions are giving errors indicating that the props are not defined. The error specifically relates to the word "props" in the following functions: function PostButton(props) function PostButton2(props) function TotalVotes(props) ...