<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>signalr tutorial &#8211; ASP.NET Hosting Reviews and Guides</title>
	<atom:link href="https://topreviewhostingasp.net/tag/signalr-tutorial/feed/" rel="self" type="application/rss+xml" />
	<link>https://topreviewhostingasp.net</link>
	<description>ASP.NET Hosting &#124; Reviews &#124; Tips &#38; Tutorial</description>
	<lastBuildDate>Fri, 23 Apr 2021 07:41:27 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	

<image>
	<url>https://topreviewhostingasp.net/wp-content/uploads/2017/01/cropped-trhaico-32x32.png</url>
	<title>signalr tutorial &#8211; ASP.NET Hosting Reviews and Guides</title>
	<link>https://topreviewhostingasp.net</link>
	<width>32</width>
	<height>32</height>
</image> 
	<item>
		<title>How to Combine ASP.NET Core SignalR Chat with Angular 5</title>
		<link>https://topreviewhostingasp.net/how-to-combine-asp-net-core-signalr-chat-with-angular-5/</link>
					<comments>https://topreviewhostingasp.net/how-to-combine-asp-net-core-signalr-chat-with-angular-5/#respond</comments>
		
		<dc:creator><![CDATA[Jacques Hunt]]></dc:creator>
		<pubDate>Fri, 23 Apr 2021 07:39:28 +0000</pubDate>
				<category><![CDATA[Hosting Tips]]></category>
		<category><![CDATA[angular 5]]></category>
		<category><![CDATA[angular 5 tutorial]]></category>
		<category><![CDATA[angular tips]]></category>
		<category><![CDATA[asp net core]]></category>
		<category><![CDATA[asp net core tips]]></category>
		<category><![CDATA[asp net core tutorial]]></category>
		<category><![CDATA[signalr]]></category>
		<category><![CDATA[signalr tips]]></category>
		<category><![CDATA[signalr tutorial]]></category>
		<guid isPermaLink="false">https://topreviewhostingasp.net/?p=2952</guid>

					<description><![CDATA[In this post, I will show an article how to use command line prompt with dotnet CLI and Angular CLI. Let&#8217;s get started. Create the Projects We will create a new empty ASP.NET Core Web project. You can either do it with Visual Studio or execute dotnet new web in the command line. I have Angular CLI installed on [&#8230;]]]></description>
										<content:encoded><![CDATA[
<p>In this post, I will show an article how to use command line prompt with dotnet CLI and Angular CLI. Let&#8217;s get started.</p>



<h2 class="wp-block-heading">Create the Projects</h2>



<p>We will create a new empty ASP.NET Core Web project. You can either do it with Visual Studio or execute<strong><em> dotnet new web</em></strong> in the command line.</p>



<p>I have Angular CLI installed on my machine. If you don’t either install it or create a new empty Angular application. I am using Angular CLI 1.5 and creating a new project with it – Angular 5 application.</p>



<p>I will just execute <em><strong>ng new CodingBlastChat </strong></em>in the command line, inside of solution folder. And now I have basic working Angular application. To start it, I just type in <em><strong>ng serve</strong></em> and I my application is running on <em>localhost</em> port <em>4200.</em></p>



<div class="wp-block-image">
<figure class="aligncenter size-large"><a href="https://www.asphostportal.com"><img fetchpriority="high" decoding="async" width="300" height="271" class="wp-image-2953 aligncenter" src="https://topreviewhostingasp.net/wp-content/uploads/2021/04/ahp-banner-aspnet-mvc-01.png" alt="" srcset="https://topreviewhostingasp.net/wp-content/uploads/2021/04/ahp-banner-aspnet-mvc-01.png 300w, https://topreviewhostingasp.net/wp-content/uploads/2021/04/ahp-banner-aspnet-mvc-01-50x45.png 50w" sizes="(max-width: 300px) 100vw, 300px" /></a></figure>
</div>



<h2 class="wp-block-heading">Installing dependencies</h2>



<p>We need to install both server-side and client-side libraries for ASP.NET Core SignalR.</p>



<p>To install the server-side library we will use NuGet. You can either use Visual Studio or do it via command line. The package name is <em>Microsoft.AspNetCore.SignalR</em></p>



<p><strong><em>dotnet add package Microsoft.AspNetCore.SignalR</em></strong></p>



<p>We will use npm to add client-side library:</p>



<p><strong><em>npm install @aspnet/</em>signalr<em>-client</em></strong></p>



<p>If you are using npm 4 or older you will need to add the<em> –save</em> argument, if you want it to be saved inside of your package.json as well. And that’s it for library dependencies. We are all set and we can now use SignalR.</p>



<h2 class="wp-block-heading">Setting up server-side</h2>



<p>We can now add the simple ChatHub class:</p>



<pre class="wp-block-code"><code>public class ChatHub : Hub
{
    public void SendToAll(string name, string message)
    {
        Clients.All.InvokeAsync("sendToAll", name, message);
    }
} </code></pre>



<p>This will call the <em>sendToAll </em>client method for ALL clients.</p>



<p>For SignalR to work we have to add it to DI Container inside of <em>ConfigureServices</em> method in Startup class:</p>



<pre class="wp-block-code"><code>services.AddSignalR();
</code></pre>



<p>Also, we have to tell the middleware pipeline that we will be using SignalR. When the request comes to the <em>/chat</em> endpoint we want our ChatHub to take over and handle it.</p>



<pre class="wp-block-code"><code>public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseSignalR(routes =&gt;
    {
        routes.MapHub&lt;ChatHub&gt;("chat");
    });
} </code></pre>



<h2 class="wp-block-heading">Enabling CORS</h2>



<p>Since we will be serving the Angular application on a separate port, for it to be able to access the SignalR server we will need to enable CORS on the Server.</p>



<p>Add the following inside of <em>ConfigureServices</em>, just before the code that adds SignalR to DI container.</p>



<pre class="wp-block-code"><code>services.AddCors(o =&gt; o.AddPolicy("CorsPolicy", builder =&gt;
    {
        builder
        .AllowAnyMethod()
        .AllowAnyHeader()
        .WithOrigins("http://localhost:4200");
    }));</code></pre>



<p>We also have to tell the middleware to use this CORS policy. Add the following inside of Configure method, BEFORE SignalR:</p>



<pre class="wp-block-code"><code>app.UseCors("CorsPolicy");
</code></pre>



<p>Now your Configure method should look like this:</p>



<pre class="wp-block-code"><code>public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
    if (env.IsDevelopment())
    {
        app.UseDeveloperExceptionPage();
    }

    app.UseCors("CorsPolicy");

    app.UseSignalR(routes =&gt;
    {
        routes.MapHub&lt;ChatHub&gt;("chat");
    });
}</code></pre>



<p>Also, make sure to check your Properties/launchSettings.json file so you can know which port is your app running. You can also configure it to use any port you want. I will set it to 5000.</p>



<h2 class="wp-block-heading">Client-side</h2>



<p>You would ideally want to have a separate service for communicating with ChatHub on the server. Also, you would want to store your endpoints in some kind of Angular service for constants. But for the simplicity sake, we will skip that for now and add it after we make the chat functional.</p>



<p>I will use existing <em>AppComponent</em> that Angular CLI created, and extend it.</p>



<p>I will add properties for nick, message and list of messages. Also, I will add a property for <em>HubConnection</em>.</p>



<pre class="wp-block-code"><code>import { Component } from '@angular/core';
import { HubConnection } from '@aspnet/signalr-client';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  private hubConnection: HubConnection;
  nick = '';
  message = '';
  messages: string[] = [];
}</code></pre>



<p>HubConnection is part of the signalr-client library built by ASP.NET team. And we will use it to establish the connection with the server and also to send messages and listen for messages from the server.</p>



<p>We will establish the connection before any other code runs in our component. Hence, we will use the OnInit event.</p>



<pre class="wp-block-code"><code>import { Component, OnInit } from '@angular/core';
import { HubConnection } from '@aspnet/signalr-client';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
  private hubConnection: HubConnection;
  nick = '';
  message = '';
  messages: string[] = [];

  ngOnInit() {
    this.nick = window.prompt('Your name:', 'John');

    this.hubConnection = new HubConnection('http://localhost:5000/chat');

    this.hubConnection
      .start()
      .then(() =&gt; console.log('Connection started!'))
      .catch(err =&gt; console.log('Error while establishing connection :('));

    }
}</code></pre>



<p>Notice the ngOnInit method. We are asking the user to enter his name and we store that inside of nick property that we created previously.</p>



<p>After that, we create the HubConnection object and try to establish the connection with the server.</p>



<p>Inside of that method, we will also add the listener for <em>sendToAll</em> event from the server:</p>



<pre class="wp-block-code"><code>this.hubConnection.on('sendToAll', (nick: string, receivedMessage: string) =&gt; {
  const text = `${nick}: ${receivedMessage}`;
  this.messages.push(text);
});</code></pre>



<p>After the event is received, we get two parameters: <em>nick</em> and the <em>message</em> itself. Now we form the new string from these two parameters and we add it to our <em>messages</em> array on AppComponent.</p>



<p>Inside of AppComponent we also need a method for sending messages from client TO server. We will use it from our view and here is the code:</p>



<pre class="wp-block-code"><code>  public sendMessage(): void {
    this.hubConnection
      .invoke('sendToAll', this.nick, this.message)
      .catch(err =&gt; console.error(err));
  }</code></pre>



<h2 class="wp-block-heading">View</h2>



<p>Now we need to set up the view. Since we plan to use the form element, we will import FormsModule in our AppModule. We will change the <em>app.module.ts</em> file.</p>



<p>We can now add the view to app.component.html:</p>



<pre class="wp-block-code"><code>&lt;div id="main-container" style="text-align:center"&gt;
  &lt;h1&gt;
    &lt;a href="https://codingblast.com/asp-net-core-signalr-simple-chat/" target="_new"&gt;
      ASP.NET Core SignalR Chat with Angular
    &lt;/a&gt;
  &lt;/h1&gt;

  &lt;div class="container"&gt;
    &lt;h2&gt;Hello {{nick}}!&lt;/h2&gt;
    &lt;form (ngSubmit)="sendMessage()" #chatForm="ngForm"&gt;
      &lt;div&gt;
        &lt;label for="message"&gt;Message&lt;/label&gt;
        &lt;input type="text" id="message" name="message" [(ngModel)]="message" required&gt;
      &lt;/div&gt;
      &lt;button type="submit" id="sendmessage" [disabled]="!chatForm.valid"&gt;
        Send
      &lt;/button&gt;
    &lt;/form&gt;
  &lt;/div&gt;

  &lt;div class="container" *ngIf="messages.length &gt; 0"&gt;
    &lt;div *ngFor="let message of messages"&gt;
      &lt;span&gt;{{message}}&lt;/span&gt;
    &lt;/div&gt;
  &lt;/div&gt;

&lt;/div&gt;</code></pre>



<p>The view has two main parts. First is a container for sending messages with a form that consists of input and button for sending the message. The second part is for listing the messages that we store inside of <em>messages</em> property on <em>AppComponent</em>. We push a new message to this array every time we get an event (message) from the ASP.NET Core SignalR server. That’s all there is to it!</p>



<p>&nbsp;</p>
]]></content:encoded>
					
					<wfw:commentRss>https://topreviewhostingasp.net/how-to-combine-asp-net-core-signalr-chat-with-angular-5/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
