SHARE:

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:

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;)

Written by

anthonygiretti

Anthony is a specialist in Web technologies (14 years of experience), in particular Microsoft .NET and learns the Cloud Azure platform. He has received twice the Microsoft MVP award and he is also certified Microsoft MCSD and Azure Fundamentals.
%d bloggers like this: