ASP.NET Core 6: Streaming JSON responses with IAsyncEnumerable, example with Angular
Introduction
What ? You did not know it? ASP.NET Core 6 now allows you to stream JSON responses! You do not believe me? Take a look at the following tweet from David Fowler:
We added native support for IAsyncEnumerable<T> into the JSON serializer in .NET 6. This means you can properly stream JSON responses to and from the client. Here’s an example using minimal APIs. #dotnet #aspnetcore pic.twitter.com/Yq1UpcpxSP— David Fowler 🇧🇧💉💉 (@davidfowl) September 11, 2021
Do you believe me now ? I hope so now. I will show you how to use it in an Angular app.
Server-side
I pass the details on the dependency injection of the CountryServices service and the dbContext CountryService, the code should look like this:
As you can see I asynchronously output the countries and the JSON serializer steams them to the client. Don’t forget to setup your CORS rules!
Client-side
So here it’s quite special, it is not possible to stream answers with RxJs and its famous Observable. What you will have to do here is use a library that will be able to manage streamed JSON responses. The library is called oboe.js.
After creating your Angular project download with the following commands the necessary packages:
npm install oboe
npm install --save @types/oboe
What you have to do here is to setup your API call configuration, instantiate an oboe object and invoke the node method as follow:
Note that the first parameter of the node method allows to handle each a streamed JSON item with the following value: !.*. In other word each time a streamed country is received by the client, the second parameter, a callback will be invoked. If you want to wait the entire response to be stream before behind handled by the callback, use the following value instead: !.
Demo
So that you believe me;)