DZone
Thanks for visiting DZone today,
Edit Profile
  • Manage Email Subscriptions
  • How to Post to DZone
  • Article Submission Guidelines
Sign Out View Profile
  • Post an Article
  • Manage My Drafts
Over 2 million developers have joined DZone.
Log In / Join
Please enter at least three characters to search
Refcards Trend Reports
Events Video Library
Refcards
Trend Reports

Events

View Events Video Library

Zones

Culture and Methodologies Agile Career Development Methodologies Team Management
Data Engineering AI/ML Big Data Data Databases IoT
Software Design and Architecture Cloud Architecture Containers Integration Microservices Performance Security
Coding Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks
Culture and Methodologies
Agile Career Development Methodologies Team Management
Data Engineering
AI/ML Big Data Data Databases IoT
Software Design and Architecture
Cloud Architecture Containers Integration Microservices Performance Security
Coding
Frameworks Java JavaScript Languages Tools
Testing, Deployment, and Maintenance
Deployment DevOps and CI/CD Maintenance Monitoring and Observability Testing, Tools, and Frameworks

The software you build is only as secure as the code that powers it. Learn how malicious code creeps into your software supply chain.

Apache Cassandra combines the benefits of major NoSQL databases to support data management needs not covered by traditional RDBMS vendors.

Generative AI has transformed nearly every industry. How can you leverage GenAI to improve your productivity and efficiency?

Modernize your data layer. Learn how to design cloud-native database architectures to meet the evolving demands of AI and GenAI workloads.

Related

  • Why Angular and ASP.NET Core Make a Winning Team
  • Code Play #1: WebSockets With Vert.x and Angular
  • Event Emitter Example with Angular 7
  • Server-Side Pagination Using ASP.NET Core and Angular 8 - Part Three

Trending

  • Can You Run a MariaDB Cluster on a $150 Kubernetes Lab? I Gave It a Shot
  • Ethical AI in Agile
  • A Modern Stack for Building Scalable Systems
  • How To Introduce a New API Quickly Using Quarkus and ChatGPT
  1. DZone
  2. Coding
  3. Frameworks
  4. A Better Way of Using ASP.NET SignalR With Angular JS

A Better Way of Using ASP.NET SignalR With Angular JS

By 
Rabi Kiran Srirangam user avatar
Rabi Kiran Srirangam
·
Sep. 20, 13 · Interview
Likes (0)
Comment
Save
Tweet
Share
27.2K Views

Join the DZone community and get the full member experience.

Join For Free

A few days back, I blogged on using SignalR and Angular JS together and on Implementing SignalR stock ticker sample using Angular JS(Part 1 and Part 2). In those posts, I have used the traditional call-back model to call the functions defined in controller to modify data whenever an update is received from the server. 

One of the readers sent me feedback saying that we have a better way to use SignalR and Angular JS together. The way to go is using event methods defined on $rootscope object. This approach is based on publishing and subscribing events. As events can be published from anywhere and subscribed from anywhere, the source and destination will remain completely unaware of each other. Both of them have to depend on just one object, $rootScope. 

Official documentation on scope contains details on each method defined on $rootScope. We will be using the following methods for publishing and subscribing the events: 

  • $emit(name, args): Publishes an event with specified name with given arguments
  • $on(name, listener): Subscribes to an event with specified name. Listener is a function containing logic to be executed once the event has occurred


To manage SignalR’s client functionality, it is better to create a service, as services are singletons. There will be only one instance of the service in entire application. This behaviour of services makes it possible to have multiple SignalR client pages in the applications and they can be kept in sync without putting any extra amount of effort. 

Let’s modify the example discussed in the post titled Hooking up ASP.NET SignalR with Angular JS to use event model. Server hub, references and structure of the HTML page remains the same as past. The only components to be modified are Controller and Service. 

Service carries the responsibility to initialize a connection to the hub and call the SignalR’s server methods. Once a response is received from the server, we will broadcast an event from the service with data received. 

app.service('signalRSvc', function ($, $rootScope) {
    var proxy = null;

    var initialize = function () {
        //Getting the connection object
        connection = $.hubConnection();

        //Creating proxy
        this.proxy = connection.createHubProxy('helloWorldHub');

        //Starting connection
        connection.start();

        //Publishing an event when server pushes a greeting message
        this.proxy.on('acceptGreet', function (message) {
            $rootScope.$emit("acceptGreet",message);
        });
    };

    var sendRequest = function () {
        //Invoking greetAll method defined in hub
        this.proxy.invoke('greetAll');
    };

    return {
        initialize: initialize,
        sendRequest: sendRequest
    }; 
});

To keep the things simple, I kept names of the server hub event and event rose using $emit the same. The names can be different. Let’s modify the controller to have a listener to the event raised by the service. Following is the implementation of the controller: 

function SignalRAngularCtrl($scope, signalRSvc, $rootScope) {
    $scope.text = "";

    $scope.greetAll = function () {
        signalRSvc.sendRequest();
    }

    updateGreetingMessage = function (text) {
        $scope.text = text;
    }

    signalRSvc.initialize();

    //Updating greeting message after receiving a message through the event

    $scope.$parent.$on("acceptGreet", function (e,message) {
        $scope.$apply(function () {
            updateGreetingMessage(message)
        });
    });
}

Now open the modified page on multiple browsers and click the Greeting button randomly from all browsers. Messages printed on all browsers should be updated whenever the button is clicked. This behaviour is same as it was earlier. We just adopted a better approach to make it work. 

Happy coding!

ASP.NET AngularJS Event

Published at DZone with permission of Rabi Kiran Srirangam, DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

Related

  • Why Angular and ASP.NET Core Make a Winning Team
  • Code Play #1: WebSockets With Vert.x and Angular
  • Event Emitter Example with Angular 7
  • Server-Side Pagination Using ASP.NET Core and Angular 8 - Part Three

Partner Resources

×

Comments
Oops! Something Went Wrong

The likes didn't load as expected. Please refresh the page and try again.

ABOUT US

  • About DZone
  • Support and feedback
  • Community research
  • Sitemap

ADVERTISE

  • Advertise with DZone

CONTRIBUTE ON DZONE

  • Article Submission Guidelines
  • Become a Contributor
  • Core Program
  • Visit the Writers' Zone

LEGAL

  • Terms of Service
  • Privacy Policy

CONTACT US

  • 3343 Perimeter Hill Drive
  • Suite 100
  • Nashville, TN 37211
  • support@dzone.com

Let's be friends:

Likes
There are no likes...yet! 👀
Be the first to like this post!
It looks like you're not logged in.
Sign in to see who liked this post!