[Fixed] How to emit a stream from .NET Core Rest API to consume in Angular as observable?

Issue

I’d like to setup a page that continuously receives values from the backend, so that the rendered data set grows with time until the backend says it’s done (which may even never happen). Something like in this article but with backend based on .NET Core.

So, the Angular service looks like this at first.

@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 issue I’m having is on the backend side. When I return the set of things, I finish off with providing Ok() specifying that the operation has completed successfully, status code 200. Now, what I’d like to achieve is to return a single thing at a time (or an array of things, as long as it’s not the final set of all things to be served). Basically, I’d like to emit values from .NET API without finalizing the connection. For simplicity, we can even work with responses of type String instead of Thing.

Is it possible at all using "the usuals" in .NET? I’m thinking the default GET method like so.

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

I’ve googled the matter but found nothing of relevance. There’s a lot of resources dealing with the Angular side and observables, RxJs etc. All the examples connecting .NET and Angular present serve-and-finalize type of connection. The best one I’ve found is linked at the top and doesn’t use .NET on the back. Somehow, I’m getting the suspicion that it’s extremely simple or nearly not doable.

Solution

If you need a long-lived connection between client and server you could look into using WebSockets through something like Pusher, which has a .NET lib available: https://github.com/pusher/pusher-http-dotnet

Alternatively you could use long-polling, although that is much less efficient because you’re intermittently querying the server for updates. You’d basically setup an Interval observable to make a request every N seconds to check for updates on the server.

Leave a Reply

(*) Required, Your email will not be published