Given a 'default' Blazor app - created using the Visual Studio 2019 Blazor server template. How do you create a GLOBAL object that is accessible from all the razor pages and components.
How would you make the 'Current Count ' value - visible and 'dynamically' updated on the MainLayout, NavMenu, Index pages?
Current count: @currentCount
[Parameters]? [CascadingParameter]?One way to do this is to is to use a singleton service that is injected into the components that allows event subscriptions. I discussed this with someone else a few days ago actually.
Check out this post for a discussion on dynamically updating pages from events fired out from a singleton, that updates across connections.
Here is a working demo that I adapted from another project I'm working on, when you run this project it instructs you to open another browser, copy / paste the URL, and has a running counter that updates and a text box to use to pass messages between pages. Enter something in the box, click the button, the counter updates on all pages from all connected clients and the message passes to all pages as well and displays. Works cross-browser and across connections.
A similar concept could be used to build up things like background notifications of long running tasks, user logon notifications, etc. Pretty flexible for my needs.
There is two ways of doing this.
CascadingParameter and "State Container" that are very well explained in this article.
Between CascadingParameter and "State Container", you are the one that should know how your application works and decide what to do.
Probably state container would be better for something like GLOBAL object that is accessible from all the razor pages and components.
Use [Parameters]?
Instead of passing all parameters down to components, you should use CascadingParameter
Create a Static Class ?
Instead of creating a static class, you should use "State Container"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With