How to Connect MVC Signalr Hub To Angular 6 web site

How to Connect MVC Signalr Hub To Angular 6 web site 

Firstly you need to install nuget package for Create Hub in web api
for install package 
1). open nuget package manage :- (first Create Project )
    1)  Open Visual Studio go to > File >New Project Choose ASP.Net MVC application.
    2). Used MVC. Check Web API reference then hit ok button
    3). Right click the project > Manage NuGet package > Browse to install
          write command nuget package manager console
                "Install-Package Microsoft.AspNet.SignalR."

2). now you need to create hub class 

using System.Linq;
using System.Web;
using Microsoft.AspNet.SignalR;
using Microsoft.AspNet.SignalR.Hubs;

namespace Tritex.Api
    public class NotificationHub : Hub
        public void NotificationService(string message)

3). Create Owin startup.cs class if not avaible 

using Microsoft.Owin;  
using Owin;  
[assembly: OwinStartupAttribute(typeof(NotifSystem.Web.Startup))]  
namespace NotifSystem.Web  
    public partial class Startup  
        public void Configuration(IAppBuilder app)  

4). Now You Need to Create Controller for api

public class StudentController : ApiController
     public  IHttpActionResult  Get(int id, string name) 
     var context = Microsoft.AspNet.SignalR.GlobalHost.ConnectionManager.
     context.Clients.All.messageReceived("Get Student Called");
 return Ok("Done");

5). Now You Need to Impliment Your Agnular 6 code in Create New Service 
I Have Created Angular 6 service name "Signalr" 

import { Injectable } from '@angular/core';
declare var $: any;
export class SignalrService {
    private connection: any;
    private proxy: any;
    constructor() { }
    public initializeSignalRConnection(): void {

      // Host address with port (url) of domain where hub is published  
        const signalRServerEndPoint = 'http://localhost:57311/';

     // Initialize Connection to hubConnection by assign end url 
        this.connection = $.hubConnection(signalRServerEndPoint);

     // Create Hub Proxy By assign name of Hub in CreateHubProxy Methord
        this.proxy = this.connection.createHubProxy('SendNotificationHub');

    // After Proxy Create "messageRecive" method of Hub(server) Get Response of other Client Notificaiton and "serverMessage" is variable hold message and assign to other method  Name is "onMessageRecived" method
        this.proxy.on('messageReceived', (serverMessage) =>                   this.onMessageReceived(serverMessage));

// Now Here Connect stablish and if application is  Connected to Hub 
You Can Send Notification To Other User by This Method "broadcastMessage"
        this.connection.start().done((data: any) => {
            console.log('Connected to Notification Hub');
        }).catch((error: any) => {
            console.log('Notification Hub error -> ' + error);

// this method send message to Hub For Other Client
    public broadcastMessage(): void {
        this.proxy.invoke('notificationService', 'Welcome to Dashboard')
            .catch((error: any) => {
                console.log('broadcastMessage error -> ' + error);

// This method Recived Message from Hub send by other client
    private onMessageReceived(serverMessage: string) {
        console.log('New message received from Server: ' + serverMessage);
} And HTML Css And Web Development: How To Use Mat Table /Data Table in angular 6 And HTML Css And Web Development: How To Use Mat Table /Data Table in angular 6: How To Use Mat Table /Data Table in angular 6 Here We Are Highlight Code in red line for Toggle Button of plus and minus for Extend Ro...

How To Use Mat Table /Data Table in angular 6

How To Use Mat Table /Data Table in angular 6

Here We Are Highlight Code in red line for Toggle Button of plus and minus for Extend Row in dataTable in Mat or Mat-table

1). From " View-Users.Component.ts" File

import { join } from 'path';
import { map } from 'rxjs/operators';
import { Component, OnInit, ViewChild } from '@angular/core';
import { SearchUser } from '../../../../../models/SearchUser.model';
import { animate, state, style, transition, trigger } from '@angular/animations';
import { UserService } from '../../../../../services/user/user.service';
import { LoggerService } from '../../../../../services/log4ts/logger.service';
import { Router } from '@angular/router';
import swal from 'sweetalert2';
import { MatTableDataSource, MatPaginator, MatSort } from '@angular/material';
import { BrowserStorageService } from '../../../../../utility/browser-storage.service';
import { AuthenticationService } from '@alfresco/adf-core';
import * as moment from 'moment';
import { ApiService } from '../../../../../services/api.service';
import { SpinnerService } from '../../../../../services/spinner.service';
import { Constants } from '../../../../../constants/app.constants';

  selector: 'app-view-users',
  templateUrl: './view-users.component.html',
  styleUrls: ['./view-users.component.scss'],
  animations: [
    trigger('detailExpand', [
      state('collapsed', style({ height: '0px', minHeight: '0' })),
      state('expanded', style({ height: '*' })),
      transition('expanded <=> collapsed', animate('225ms cubic-bezier(0.4, 0.0, 0.2, 1)')),
export class ViewUsersComponent implements OnInit {
  dataSource = new MatTableDataSource();
  rowCount = 0;
  isExpansionDetailRow = null;

  error: any;
  public data: SearchUser[];
  public filterQuery = '';
  userId: string;
  responseStatus = null;
  @ViewChild('successContractSwal') successContractSwal: any;
  constructor(public userService: UserService,
    private authService: AuthenticationService,
    private apiService: ApiService,
    private spinner: SpinnerService,
    private browserStorageService: BrowserStorageService, private loggerService: LoggerService, private router: Router) {
  @ViewChild(MatSort) sort: MatSort;
  @ViewChild('MatPaginator') paginator: MatPaginator;
  displayedColumns = [
    'IsExtended', 'EmailID', 'Name', 'RoleName', 'UserBelong', 'CreatedBy', 'CreatedDate', 'Action'];
  ngOnInit() {
    this.apiService.isSpinner = false;
    this.userId = this.browserStorageService.getLocalStorageItem('userId');

  applyFilter(filterValue: string) {
    this.dataSource.filter = filterValue.trim().toLowerCase();
  public toInt(num: string) {
    return +num;
  private showPopup(type: string, title: string, text: string) {
    this.successContractSwal.type = type;
    this.successContractSwal.title = title;
    this.successContractSwal.text = text;;


  getUserdetail(UserID: any) {
    this.browserStorageService.setSessionStorageItem('TritexUuid', UserID);

  setRedirectAddUserUrl() {
    this.router.navigate(['/mastersetup/users/add-users/' + new Date().getTime() + '/' + new Date().getDate()]);

  public sortByWordLength = (a: any) => {

  public getDate(regDate: string) {
    const date = new Date(regDate);
    return date.toLocaleDateString('en-US', { year: 'numeric', month: 'short', day: '2-digit' });

  getUserData() {
    this.responseStatus = null;
    const UserRoleList = this.browserStorageService.getSessionStorageItem('UserRoleNames').split(',');
    this.userService.searchUser(UserRoleList.indexOf('SUPER_ADMIN') > -1 ?
      null : this.browserStorageService.getLocalStorageItem('userId'),
      localStorage.getItem('ticket-ECM')).then((res: any) => {
        this.responseStatus = res.status; = res.result; any) => {
          element.CreatedDate = moment(element.CreatedDate, 'DD/MM/YYYY HH:mm:ss');
          element.IsExtendedRow = false;

        this.dataSource = new MatTableDataSource(;
        // inner object filter
        this.dataSource.filterPredicate = (data: any, filter: string) => {
          const accumulator = (currentTerm, key) => {
            return key === 'UserGroupOperator' ? currentTerm + => x.Code).join('')
              + => x.Name).join('') : currentTerm + data[key];
          const dataStr = Object.keys(data).reduce(accumulator, '').toLowerCase();
          const transformedFilter = filter.trim().toLowerCase();
          return dataStr.indexOf(transformedFilter) !== -1;
        this.rowCount =;
        this.dataSource.paginator = this.paginator;
        this.dataSource.sort = this.sort;
        this.apiService.isSpinner = true;
      }).catch((error) => {
        this.apiService.isSpinner = true;
        this.error = error;
        this.showPopup('error', 'Error!', error.message);


  isExpandedRow(element) { any) => {
      if (element === data) {
        element.IsExtendedRow = !element.IsExtendedRow;
      } else {
        data.IsExtendedRow = false;



2). From " View-Users.Component.html" File

<div class="tab-container">
  <div class="box-section">
    <swal #successContractSwal title="Success!" type="success" text="" (confirm)="getUserData()"
      [options]="{ showConfirmButton: true, confirmButtonText: 'OK', confirmButtonColor: '#DD6B55' }"></swal>
    <div class="box-view box-blue" #respMessage>
      <div class="box-header bottom-border">
        <h3 class="box-header-title">User List</h3>
      <div class="form-section">
        <div class="box-body">
          <div class="row">
            <div class="col-md-1">
            <div *ngIf="data" class="col-md-11">
              <div class="col-md-3 offset-md-9 d-flex justify-content-end filter-row" style="padding-left: 10px;">
                <div class="input-group" style="margin-top: 10px;margin-bottom: 15px;">
                  <div class="input-group-prepend">
                    <span class="input-group-text">
                      <i class="fa fa-search"></i>
                  <input type="text" class="form-control" (keyup)="applyFilter($"
          <div class="row" style="margin-bottom: 15px;">
            <div class="col-md-12">
              <div class="workflow-table custom-table-responsive">
                <div class="example-container mat-elevation-z8">

                  <mat-table #table mat-table matSort [dataSource]="dataSource" multiTemplateDataRows
                    <mat-header-row *matHeaderRowDef="displayedColumns"></mat-header-row>

                    <ng-container matColumnDef="IsExtended">
                      <mat-header-cell *matHeaderCellDef mat-sort-header></mat-header-cell>
                      <mat-cell *matCellDef="let element" style="justify-content: center;">
                        <!-- <i [ngClass]="{'fa fa-plus': !element.IsExtendedRow, 'fa fa-minus': element.IsExtendedRow}"></i> -->
                        <i class="{{!element.IsExtendedRow ? 'fa fa-plus' : 'fa fa-minus'}}"></i>

                    <ng-container matColumnDef="EmailID">
                      <mat-header-cell *matHeaderCellDef mat-sort-header> EmailID </mat-header-cell>
                      <mat-cell *matCellDef="let element">
                        <a href="JavaScript:void(0);" (click)="getUserdetail(element.UserID)">

                    <ng-container matColumnDef="Name">
                      <mat-header-cell *matHeaderCellDef mat-sort-header> Name </mat-header-cell>
                      <mat-cell *matCellDef="let element">{{ element.Name }}</mat-cell>
                    <ng-container matColumnDef="RoleName">
                      <mat-header-cell *matHeaderCellDef mat-sort-header> Role's </mat-header-cell>
                      <mat-cell *matCellDef="let element">{{ element.RoleName | permissionPipe}}</mat-cell>

                    <ng-container matColumnDef="UserBelong">
                      <mat-header-cell *matHeaderCellDef mat-sort-header>User Belong </mat-header-cell>
                      <mat-cell *matCellDef="let element">{{ element.UserBelong }}</mat-cell>

                    <ng-container matColumnDef="CreatedBy">
                      <mat-header-cell *matHeaderCellDef mat-sort-header> Created By</mat-header-cell>
                      <mat-cell *matCellDef="let element">{{ element.CreatedBy }}</mat-cell>

                    <ng-container matColumnDef="CreatedDate">
                      <mat-header-cell *matHeaderCellDef mat-sort-header> Created Date</mat-header-cell>
                      <mat-cell *matCellDef="let element">{{ element.CreatedDate | date : 'dd/MM/yyyy HH:mm:ss'}}

                    <ng-container matColumnDef="Action">
                      <mat-header-cell *matHeaderCellDef> Action </mat-header-cell>
                      <mat-cell *matCellDef="let element">
                        <a href="JavaScript:void(0);" tooltip="Click to release lock" placement="bottom"
                          (click)="LockUser(element)" *ngIf="element.isAccountLocked">
                          <i class="fa fa-lock" aria-hidden="true"></i>

                    <ng-container matColumnDef="noData">
                      <mat-footer-cell *matFooterCellDef colspan="8">
                        Whoa! No User Data Found !

                    <ng-container matColumnDef="expandedDetail">
                      <mat-cell *matCellDef="let detail" class="period-bg-ligt-blue">
                        <ng-container *ngIf="detail.UserGroupOperator.length==0">
                          no record found
                        <ng-container class="row" *ngIf="detail.UserGroupOperator.length>0">
                          <div class="col-md-6 col-sm-12">
                            <table class="table table-responsive-sm table-bordered table-sm">
                                <ng-container *ngFor="let item of detail.UserGroupOperator">
                                    <td style="text-align: center;"> <i *ngIf="item.IsTritex"
                                        class="fa fa fa-check"></i>

                    <mat-row *matRowDef="let row; columns: displayedColumns;" matRipple class="element-row"
                      [class.expanded]="expandedElement == row"
                      (click)="(expandedElement !== row)? expandedElement = row:expandedElement=[]; isExpandedRow(row)">

                    <mat-row *matRowDef="let row; columns: ['expandedDetail'];when: isExpansionDetailRow"
                      [@detailExpand]="(row == expandedElement && row.UserGroupOperator.length>0) ? 'expanded' : 'collapsed'"
                      style="overflow: hidden">

                    <mat-footer-row *matFooterRowDef="['noData']"
                      [ngClass]="{'hide':!(rowCount=== 0 && responseStatus)}">

                  <mat-paginator #MatPaginator [pageSize]="50" [pageSizeOptions]="[5, 10, 20,50,100]"



import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { Routes, RouterModule } from '@angular/router';
import { ReactiveFormsModule, FormsModule } from '@angular/forms';
import { NgMultiSelectDropDownModule } from 'ng-multiselect-dropdown';

import {
  MatDatepickerModule, MatTableModule,
} from '@angular/material';
import { SweetAlert2Module } from '@toverux/ngx-sweetalert2';
import { NgSelectModule } from '@ng-select/ng-select';
// import { DataTableModule } from 'angular2-datatable';
import { DataFilterPipeModule } from '../../../../pipes/data-filter-pipe.module';
import { BsDropdownModule } from 'ngx-bootstrap';
import { CustomModalModule } from '../../../../modal/custom-modal.module';
import { ViewUsersComponent } from './view-users/view-users.component';
import { TooltipModule } from 'ngx-bootstrap';
import { ProfileModule } from '../../profile/profile.module';
const routes: Routes = [
    path: '',
    component: ViewUsersComponent,
    data: {
      title: 'Search'
    path: 'add-users/:refresh1',
    component: AddUsersComponent,
    data: {
      title: 'Add'
    path: 'add-users/:refresh1/:refresh2',
    component: AddUsersComponent,
    data: {
      title: 'Edit'
    path: 'view-users/:refresh',
    component: ViewUsersComponent,
    data: {
      title: 'Search'
  imports: [
  declarations: [ ViewUsersComponent]
export class UsersModule { }

Featured Post

How to remove all quick access file from computer in one time

 How to remove all quick access file from computer in one time  step1: first at all press "Window+R" then open a Run dialog box an...

Popular Posts