6

ASP.NET Core 6: Streaming JSON responses with IAsyncEnumerable, example with Ang...

 2 years ago
source link: https://anthonygiretti.com/2021/09/22/asp-net-core-6-streaming-json-responses-with-iasyncenumerable-example-with-angular/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

ASP.NET Core 6: Streaming JSON responses with IAsyncEnumerable, example with Angular

2021-09-22 by anthonygiretti

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:

var builder = WebApplication.CreateBuilder(args);

builder.Services.AddScoped<ICountryServices, CountryServices>(); builder.Services.AddDbContext<CountryContext>(options => options.UseSqlServer(builder.Configuration.GetConnectionString("CountryService"))); builder.Services.AddCors(o => o.AddPolicy("AllowAll", builder => { builder.AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader(); }));

var app = builder.Build();

app.UseCors("AllowAll");

app.MapGet("/stream/countries", async (ICountryServices countryServices) => { async IAsyncEnumerable<CountryModel> StreamCountriesAsync() { var countries = await countryServices.GetAllAsync(); foreach (var country in countries) { await Task.Delay(500); yield return country; } } return StreamCountriesAsync(); });

// Run the app app.Run();

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:

import { Component, OnInit } from '@angular/core'; import { CountryModel } from '../models/countryModel'; import * as oboe from 'oboe';

@Component({ selector: 'app-json-streaming', templateUrl: './json-streaming.component.html', styleUrls: ['./json-streaming.component.css'] }) export class JsonStreamingComponent implements OnInit {

public countries: CountryModel[] = []; constructor() { }

ngOnInit(): void { var config = { 'url': "https://localhost:5001/stream/countries", 'method': "GET", 'cached': false } const oboeService = oboe(config); var that = this; oboeService.node('!.*', function (country: CountryModel) { that.countries.push(country); }); } }

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: !.

So that you believe me;)

Like this:

Loading...

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK