How can a .NET Core Rest API emit a stream to be consumed in Angular as an observable?

I'm interested in creating a dynamic page that continuously fetches data from the backend, allowing the data set to grow over time until the backend indicates completion (which may never happen). Similar to the concept discussed in this article, but utilizing a backend based on .NET Core.

Initially, the Angular service would appear as follows.

@Injectable()
export class TheService {
  constructor(private httpClient: HttpClient) {}
  getStuff(): Observable<Thing[]> {
    return this.httpClient.get<Thing[]>('http://localhost:3000/stuff');
  }
  getThing(): Observable<Thing> {
    return this.httpClient.get<Thing>('http://localhost:3000/thing');
  }
}

The challenge lies on the backend side. When returning a collection of things, the operation is completed with Ok() indicating a successful status code of 200. However, I aim to return one thing at a time (or an array of things without completing the final data set). Essentially, I want to emit values from the .NET API without closing the connection. As a simplification, using responses of type String instead of Thing is acceptable.

Is this achievable using common practices in .NET? I'm referring to the default GET method as shown below.

[HttpGet("stuff")]
public ActionResult<IEnumerable<Thing>> GetThing()
{
  IEnumerable<Thing> output = ...;
  return Ok(output);
}
[HttpGet("thing")]
public ActionResult<Thing> GetThing()
{
  Thing output = ...;
  return Ok(output);
}

After researching extensively, I have not come across relevant information. While there are numerous resources on the Angular side, focusing on observables, RxJs, etc., most examples of integrating .NET and Angular involve a serve-and-finalize connection. The best example I found, linked at the beginning, does not involve .NET on the backend. I suspect that the solution may be simpler than expected, or possibly challenging to implement.

Answer №1

If you're seeking a persistent connection between client and server, consider exploring the option of utilizing WebSockets, which can be implemented through services like Pusher. Pusher offers a .NET library that you can access here: https://github.com/pusher/pusher-http-dotnet

Another approach would be to use long-polling, although this method is less efficient as it involves making periodic queries to the server for updates. Essentially, you would set up an Interval observable to send a request every N seconds to check for any new information on the server.

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

What is the process for running a continuous stream listener in a node.js function?

I am currently working with a file called stream.ts: require('envkey') import Twitter from 'twitter-lite'; const mainFn = async () => { const client = new Twitter({ consumer_key: process.env['TWITTER_CONSUMER_KEY'], ...

Discovering if a class in C# is a specific instance of a generic interface: A guide

Is it possible to obtain an instance of Property<T> as Property and execute its methods without knowing the generic type parameter T? private interface Property<T> { T Value { get;} void DestroyEarth(); } class MyProperty : Property& ...

Initializing Page Elements with Selenium 4 using PageFactory

I am currently in the process of upgrading my outdated Selenium library to the latest version. However, I'm encountering issues with the PageFactory.InitElements method, which is not available in the default Selenium 4 but can be found in DotNetSeleni ...

The Azure GraphQL serverless function encountering an issue with the Cosmos DB connection, displaying an

After developing a serverless GraphQL API function using Azure functions and connecting it to Cosmos DB, I have encountered an issue with "Invalid URL" that has been puzzling me for a week. Despite running the graphql function locally without any problems, ...

Exporting HTML content into an Excel spreadsheet while ensuring that the leading is

public void ConvertHtmlToExcel(string htmlContent, string fileName, out string errorMessage) { errorMessage = ""; try { fileName = fileName == "" ? "Exp ...

Dynamic starting point iteration in javascript

I'm currently working on a logic that involves looping and logging custom starting point indexes based on specific conditions. For instance, if the current index is not 0, the count will increment. Here is a sample array data: const data = [ { ...

Guide on incorporating external .d.ts files for a module

I'm currently delving into the process of utilizing an external .d.ts file that is not included in the module. My intention is to make use of xlsx, which lacks its own type definitions, and instead incorporate them from the package @types/xlsx. Afte ...

Unlock the power of trackBy when using AsyncPipe for rendering images and stop unnecessary page re-rendering

I'm having an issue with using trackBy on the Async pipe while rendering images underneath it. Here's what I've tried: <div *ngFor="let friend of friends$ | async;trackBy:trackByFn"> <img [src]="friend.image"> </div> ...

NextJS VSCode Typescript results in breakpoints becoming unbound

I have been following the instructions provided by Next.js from their official documentation on debugging using Visual Studio Code found here: https://nextjs.org/docs/advanced-features/debugging#using-the-debugger-in-visual-studio-code When attempting to ...

Utilizing trackingjs as an external library in Ionic2

I have been attempting to incorporate the trackingjs library (https://www.npmjs.com/package/tracking) into my ionic2 project. Following the guidelines in the documentation (https://ionicframework.com/docs/v2/resources/third-party-libs/), I was able to suc ...

What is the most effective way to decode this JSON file within an MVC framework?

"equipmentList": [ { "serial": "54D-894612-457-32", "category": "storage", "subcategory": "private", "type": "dataVault", "nickname": "DSC", &qu ...

Incorporating an Angular 2 Directive within the body tag of an

My goal is to create a custom directive that can dynamically add or remove a class from the body element in HTML. The directive needs to be controlled by a service, as I want to manage the visibility of the class from various components. Question: How ca ...

Access your Angular 2 application on an external device during the development process

Is there a way to view your app in an external device like a cell phone web browser, instead of just running npm start and viewing it in your desktop browser? ...

The speed of Ping is unbearably sluggish

My task involves pinging 167 IPs, but no matter the timeout setting (100ms or 1ms) and whether I use async/await, Task.Run(), or neither, the results consistently take around 80 seconds! List<PingResult> res = new List<PingResult>(); var model ...

The concept of overloaded function types in TypeScript

Is it possible to create an overloaded function type without specifying a concrete function? By examining the type of an overloaded function, it appears that using multiple call signatures on an interface or object type is the recommended approach: functi ...

Converting a JSON object to a class in ASP.NET MVC - A step-by-step guide

Having trouble converting the JSON object below to a class in Asp.Net MVC. { "Name.Test":"fsafasfda" } If you have any suggestions, they are greatly appreciated. The situation is as follows in an ASP.NET action: [HttpPut] public JsonResult Te ...

Navigate to the login page in Angular 2

Initially, the template login (login.component) needs to be called first. Once the login is complete, then app.component will be loaded. Is it possible to achieve this? And if so, how can I do it? Edited Question: I am already using CanActivate. Apologi ...

Run a script in a newly opened tab using the chrome.tabs.create() method

Struggling with executing a script using chrome.tabs.executeScript() in the tab created with chrome.tabs.create()? Despite searching for solutions, nothing seems to be working as expected. Check out my current code below: runContentScript(){ c ...

The "library" is encountering errors due to missing dependencies, specifically @angular/material/form-field

I've been working with a shared component library project that has been running smoothly for a while now. Recently, I decided to replace some of the custom components with Angular Material components. However, after adding NgMat to the library project ...

Specialized typescript function that is compatible with extended interfaces

Is there a way to create a versatile function that can be applied to any interface derived from a top-level interface? This function should take an unpersisted interface (without an id property) and return a persisted one (with an id property). The two ma ...