In this article, we will create an online polling application using ASP.NET Core, Angular 5, and the Entity Framework Core. Since this is the season of Indian Premiere League cricket in India, we will create an online poll for “Who is going to win IPL 2018?” The poll results will be displayed as a column chart that is created using Highcharts.
在本文中,我们将使用ASP.NET Core,Angular 5和Entity Framework Core创建一个在线轮询应用程序。 由于这是印度的印度超级联赛板球比赛的季节,我们将为“谁将赢得IPL 2018?”进行在线调查。 投票结果将显示为使用Highcharts创建的柱形图。
We will use Visual Studio 2017 and SQL Server 2014.
我们将使用Visual Studio 2017和SQL Server 2014。
Take a look at the final application.
看一下最终的应用程序。
Install .NET Core 2.0.0 or above SDK from here.
从此处安装.NET Core 2.0.0或更高版本的SDK。
Install the latest version of Visual Studio 2017 Community Edition from here.
从此处安装最新版本的Visual Studio 2017社区版。
Download and install the latest version of Node.js from here.
从此处下载并安装最新版本的Node.js。
Before proceeding, I would recommend that you to get the source code from GitHub.
在继续之前,我建议您从GitHub获取源代码。
We will store the team data in the IplTeams table. Execute the following commands to create the table.
我们将团队数据存储在IplTeams表中。 执行以下命令来创建表。
CREATE TABLE IplTeams ( TeamId INTEGER IDENTITY(1,1) PRIMARY KEY, TeamName VARCHAR(30) NOT NULL, VoteCount INTEGER NOT NULL )
Now, we will put in the team names and initialize the vote count to zero. Execute the following insert statements.
现在,我们将输入团队名称并将投票数初始化为零。 执行以下插入语句。
INSERT INTO IplTeams VALUES ('Chennai Super Kings',0) INSERT INTO IplTeams VALUES ('Delhi Daredevils',0) INSERT INTO IplTeams VALUES ('Kings XI Punjab',0) INSERT INTO IplTeams VALUES ('Kolkata Knight Riders',0) INSERT INTO IplTeams VALUES ('Mumbai Indians',0) INSERT INTO IplTeams VALUES ('Rajasthan Royals',0) INSERT INTO IplTeams VALUES ('Royal Challengers Bangalore',0) INSERT INTO IplTeams VALUES ('Sunrisers Hyderabad',0)
Open Visual Studio and select File >> New >> Project. After selecting the project, a “New Project” dialog will open. Select .NET Core inside the Visual C# menu from the left panel.
打开Visual Studio,然后选择“文件>>新建>>项目”。 选择项目后,将打开“新建项目”对话框。 从左侧面板的Visual C#菜单中选择.NET Core。
Then, select “ASP.NET Core Web Application” from the available project types. Put the name of the project as IPLPollDemo and press OK.
然后,从可用的项目类型中选择“ ASP.NET Core Web应用程序”。 将项目名称输入IPLPollDemo 然后按确定。
After clicking on OK, a new dialog will open asking you to select the project template. You will see two drop-down menus at the top left of the template window. Select “.NET Core” and “ASP.NET Core 2.0” from these dropdowns. Then, select the “Angular” template and press OK.
单击确定后,将打开一个新对话框,要求您选择项目模板。 您将在模板窗口的左上方看到两个下拉菜单。 从这些下拉列表中选择“ .NET Core”和“ ASP.NET Core 2.0”。 然后,选择“ Angular”模板,然后按OK。
Now our project has been created.
现在我们的项目已经创建。
Since we are using Highcharts in our application, we need to install packages for it. Open the package.json file and put the following code into it:
由于我们在应用程序中使用Highcharts,因此需要为其安装软件包。 打开package.json 文件,并将以下代码放入其中:
{ "name": "IPLPollDemo", "private": true, "version": "0.0.0", "scripts": { "test": "karma start ClientApp/test/karma.conf.js" }, "devDependencies": { "@angular/animations": "5.2.10", "@angular/common": "5.2.10", "@angular/compiler": "5.2.10", "@angular/compiler-cli": "5.2.10", "@angular/core": "5.2.10", "@angular/forms": "5.2.10", "@angular/http": "5.2.10", "@angular/platform-browser": "5.2.10", "@angular/platform-browser-dynamic": "5.2.10", "@angular/platform-server": "5.2.10", "@angular/router": "5.2.10", "@ngtools/webpack": "6.0.0-rc.10", "@types/chai": "4.1.3", "@types/highcharts": "^5.0.22", "@types/jasmine": "2.8.6", "@types/webpack-env": "1.13.6", "angular2-router-loader": "0.3.5", "angular2-template-loader": "0.6.2", "aspnet-prerendering": "^3.0.1", "aspnet-webpack": "^2.0.1", "awesome-typescript-loader": "5.0.0", "bootstrap": "4.1.1", "chai": "4.1.2", "css": "2.2.1", "css-loader": "0.28.11", "es6-shim": "0.35.3", "event-source-polyfill": "0.0.12", "expose-loader": "0.7.5", "extract-text-webpack-plugin": "3.0.2", "file-loader": "1.1.11", "html-loader": "0.5.5", "isomorphic-fetch": "2.2.1", "jasmine-core": "3.1.0", "jquery": "3.3.1", "json-loader": "0.5.7", "karma": "2.0.2", "karma-chai": "0.1.0", "karma-chrome-launcher": "2.2.0", "karma-cli": "1.0.1", "karma-jasmine": "1.1.1", "karma-webpack": "3.0.0", "preboot": "6.0.0-beta.3", "raw-loader": "0.5.1", "reflect-metadata": "0.1.12", "rxjs": "^6.0.0", "style-loader": "0.21.0", "to-string-loader": "1.1.5", "typescript": "2.8.3", "url-loader": "1.0.1", "webpack": "4.6.0", "webpack-hot-middleware": "2.22.1", "webpack-merge": "4.1.2", "zone.js": "0.8.26" }, "dependencies": { "angular-highcharts": "^5.2.12", "highcharts": "^6.1.0" } }
Here, we have added the Highcharts dependency in lines 22, 64 and 65.
在这里,我们在第22、64和65行中添加了Highcharts依赖项。
Important Note: If you have Angular version 4 in your package.json file, then copy the full code as above to update your Angular version to 5. If you are already using angular 5, then just copy the lines to include the Highcharts dependency.
重要说明:如果package.json文件中有Angular版本4,则复制上面的完整代码以将Angular版本更新为5。如果您已经在使用angular 5,则只需复制包含Highcharts依赖项的行即可。
Now, close the Visual Studio instance and navigate to the project folder containing the package.json file and open the command prompt. Execute the “npm install” command to install all the required dependencies. Refer to the image below:
现在,关闭Visual Studio实例并导航到包含package.json文件的项目文件夹,然后打开命令提示符。 执行“ npm install ”命令以安装所有必需的依赖项。 请参考下图:
After the command executes successfully, open your project in Visual Studio. You’ll see the folder structure in Solution Explorer as shown in the below image.
命令成功执行后,在Visual Studio中打开您的项目。 您将在解决方案资源管理器中看到文件夹结构,如下图所示。
Here, we have our Controllers and Views folders. We won’t be touching the Views folders for this tutorial, since we will be using Angular to handle the UI.
在这里,我们有Controllers和Views文件夹。 本教程不会涉及Views文件夹,因为我们将使用Angular来处理UI。
The Controllers folders will contain our Web API controller. We’re interested in the ClientApp folder where the client side of our application resides.
Controllers文件夹将包含我们的Web API控制器。 我们对应用程序客户端所在的ClientApp文件夹感兴趣。
Inside the ClientApp/app/components folder, we already have a few components created which are provided by default with the Angular template in VS 2017. These components won’t affect our application, but for the sake of this tutorial, we will delete the fetchdata and counter folders from ClientApp/app/components.
在ClientApp / app / components文件夹中,我们已经创建了一些组件,这些组件在VS 2017中默认情况下随Angular模板一起提供。这些组件不会影响我们的应用程序,但是出于本教程的考虑,我们将删除从ClientApp / app / components 提取数据和计数器文件夹。
We are using the Entity Framework core database’s first approach to create our models. Navigate to Tools >> NuGet Package Manager >> Package Manager Console.
我们正在使用Entity Framework核心数据库的第一种方法来创建模型。 导航到工具>> NuGet软件包管理器>>软件包管理器控制台。
We have to install the package for the database provider that we are targeting, which is SQL Server in this case. So now, run the following command:
我们必须为目标数据库提供程序安装软件包,在这种情况下为SQL Server。 因此,现在运行以下命令:
Install-Package Microsoft.EntityFrameworkCore.SqlServer
Since we are using Entity Framework Tools to create a model from the existing database, we will install the tools package as well. Run the following command:
由于我们使用实体框架工具从现有数据库创建模型,因此我们还将安装工具包。 运行以下命令:
Install-Package Microsoft.EntityFrameworkCore.Tools
After you have installed both the packages, we will scaffold our model from the database tables using the following command:
在安装完两个软件包之后,我们将使用以下命令从数据库表中构建模型:
Scaffold-DbContext "Your connection string here" Microsoft.EntityFrameworkCore.SqlServer -OutputDir Models -Tables IplTeams
Note: Do not forget to put in your own connection string (inside “ ”).
注意 :不要忘记输入自己的连接字符串(在“”内)。
After this command is executed successfully, you’ll see that a Models folder has been created and contains two class files: myTestDBContext.cs and IplTeams.cs. We have successfully created our Models using EF core database’s first approach.
成功执行此命令后,您将看到已经创建了一个Models文件夹并包含两个类文件: myTestDBContext.cs 和IplTeams.cs 。 我们已经使用EF核心数据库的第一种方法成功创建了模型。
Now, we will create one more class file to handle database related operations.
现在,我们将再创建一个类文件来处理与数据库相关的操作。
Right click on the Models folder and select Add >> Class. Name your class TeamDataAccessLayer.cs and click the Add button. At this point in time, the Models folder will have the following structure.
右键单击Models文件夹,然后选择Add >> Class。 命名类TeamDataAccessLaŸer.cs和CLICķT他添加按钮。 此时,“模型”文件夹将具有以下结构。
Open TeamDataAccessLayer.cs and put in the following code to handle database operations:
打开TeamDataAccessLayer.cs 并放入以下代码来处理数据库操作:
using Microsoft.EntityFrameworkCore; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace IPLPollDemo.Models { public class TeamDataAccessLayer { myTestDBContext db = new myTestDBContext(); //To get the list of all teams from database public IEnumerable<IplTeams> GetAllTeams() { try { return db.IplTeams.ToList(); } catch { throw; } } //To update the vote count of a team by one public int RecordVote(IplTeams iplTeam) { try { db.Database.ExecuteSqlCommand("update IplTeams set VoteCount = VoteCount + 1 where TeamID = {0}", parameters: iplTeam.TeamId); return 1; } catch { throw; } } //To get the total votes count public int GetTotalVoteCount() { try { return db.IplTeams.Sum(t => t.VoteCount); } catch { throw; } } } }
In this class we have defined three methods.
在此类中,我们定义了三种方法。
Now we will create our web API controller.
现在,我们将创建我们的Web API控制器。
Right click on the Controllers folder and select Add >> New Item.
右键单击Controllers文件夹,然后选择Add >> New Item。
An “Add New Item” dialog box will open. Select ASP.NET from the left panel, then select “Web API Controller Class” from the templates panel and name it TeamController.cs. Click Add.
“添加新项”对话框将打开。 从左侧面板中选择ASP.NET ,然后从模板面板中选择“ Web API Controller Class”,并将其命名为TeamController.cs 。 单击添加。
This will create our Web API TeamController class. We will put all our business logic in this controller. We will call the methods of TeamDataAccessLayer to fetch data and pass on the data to the Angular frontend.
这将创建我们的Web API TeamController类。 我们将所有业务逻辑放入此控制器中。 我们将调用TeamDataAccessLayer的方法 获取数据并将数据传递到Angular前端。
Open the TeamController.cs file and put the following code into it.
打开TeamController.cs 文件,并将以下代码放入其中。
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using IPLPollDemo.Models; using Microsoft.AspNetCore.Mvc; namespace IPLPollDemo.Controllers { [Route("api/Team")] public class TeamController : Controller { TeamDataAccessLayer objTeam = new TeamDataAccessLayer(); [HttpGet] [Route("GetTeamList")] public IEnumerable<IplTeams> GetTeamList() { return objTeam.GetAllTeams(); } [HttpGet] [Route("TotalVotes")] public int TotalVotes() { return objTeam.GetTotalVoteCount(); } [HttpPut] [Route("UpdateVoteCount")] public int UpdateVoteCount([FromBody] IplTeams team) { return objTeam.RecordVote(team); } } }
We will create an Angular service that will convert the Web API response to JSON and pass it to our component. Right click on the ClientApp/app folder and then Add >> New Folder and name the folder as Services.
我们将创建一个Angular服务,它将Web API响应转换为JSON并将其传递给我们的组件。 右键单击ClientApp / app文件夹,然后添加>>新文件夹并命名倍尔的Selenium [R恶习。
Right click on the Services folder and select Add >> New Item. An “Add New Item” dialog box will open. Select Scripts from the left panel, then select “TypeScript File” from the templates panel. Name it teamservice.service.ts and click Add.
右键单击Services文件夹,然后选择Add >> New Item。 “添加新项”对话框将打开。 从左侧面板中选择脚本,然后从模板面板中选择“ TypeScrip t File”。 命名为teamservice.servi ce.ts,然后单击添加。
Open the teamservice.service.ts file and put the following code into it.
打开teamservice.service.ts文件,并将以下代码放入其中。
import { Injectable, Inject } from '@angular/core'; import { Http, Response } from '@angular/http'; import { Observable } from 'rxjs/Observable'; import { Router } from '@angular/router'; import 'rxjs/add/operator/map'; import 'rxjs/add/operator/catch'; import 'rxjs/add/observable/throw'; @Injectable() export class TeamService { myAppUrl: string = ""; constructor(private _http: Http, @Inject('BASE_URL') baseUrl: string) { this.myAppUrl = baseUrl; } getTeams() { return this._http.get(this.myAppUrl + 'api/Team/GetTeamList') .map((response: Response) => response.json()) .catch(this.errorHandler); } getTotalVotes() { return this._http.get(this.myAppUrl + 'api/Team/TotalVotes') .map((response: Response) => response.json()) .catch(this.errorHandler); } saveVotes(team) { return this._http.put(this.myAppUrl + 'api/Team/UpdateVoteCount', team) .map((response: Response) => response.json()) .catch(this.errorHandler); } errorHandler(error: Response) { console.log(error); return Observable.throw(error); } }
In the constructor, we are injecting the HTTP service and Base URL of the application to enable web API calls. After that, we have defined three functions to call our Web API and convert the result to JSON format. We will call these functions from our components.
在构造函数中,我们将注入应用程序的HTTP服务和基本URL,以启用Web API调用。 之后,我们定义了三个函数来调用Web API并将结果转换为JSON格式。 我们将从组件中调用这些函数。
At this point in time, you might get the error “Parameter ‘employee’ implicitly has an ‘any’ type” in the empservice.service.ts file. If you encounter this issue, then add the following line inside the tsconfig.jsonfile:
此时,您可能会在empservice.service.ts中收到错误“参数'employee'隐式具有'any'类型” 错误 文件。 如果遇到此问题,请在tsconfig.json文件中添加以下行:
“noImplicitAny”: false
“ noImplicitAny”:否
Now, we will go on to create our components.
现在,我们将继续创建组件。
We will be adding two Angular components to our application:
我们将在我们的应用程序中添加两个Angular组件:
Right click on the ClientApp/app/components folder and select Add >> New Folder and name the folder Poll.
右键单击ClientApp / app / components 文件夹,然后选择添加>>新文件夹并命名歼奥尔德 - [R投票。
Right click on the Poll folder and select Add >> New Item. An “Add New Item” dialog box will open. Select Scripts from the left panel, then select “TypeScript File” from templates panel. Name it IPLPoll.component.ts and click Add. This will add a typescript file inside the Poll folder.
右键点击投票 文件夹,然后选择添加>>新建项目。 “添加新项”对话框将打开。 从左侧面板中选择脚本,然后从模板面板中选择“ TypeScrip t File”。 将其命名为IPLPoll.compone nt.ts,然后单击“添加”。 这将添加一个打字稿文件insidË 前作投票的文件夹。
Right click on the Poll folder and select Add >> New Item. An “Add New Item” dialog box will open. Select ASP.NET Core from the left panel, then select “HTML Page” from templates panel, and name it IPLPoll.component.html. Click Add. This will add an HTML file inside the Poll folder.
右键点击投票 文件夹,然后选择添加>>新建项目。 “添加新项”对话框将打开。 拣选ASP.NE牛逼核心从左侧面板,然后从模板面板中选择“HTML页面”,并那幺它IPLPoll.componen 牛逼的.html。 单击添加。 这将添加一个HTML文件insidË 前作投票的文件夹。
Similarly, create a Results folder inside the ClientApp/app/components folder and add a PollResult.component.ts typescript file and PollResult.component.html HTML file to it.
同样,在ClientApp / app / components中创建一个Results文件夹 文件夹,然后向其中添加PollResult.component.ts打字稿文件和PollResult.component.html HTML文件。
Now, our ClientApp/app will look like the image below.
现在,我们的ClientApp / app 如下图所示。
Open the IPLPoll.component.ts file and put the following code into it.
打开IPLPoll.component.ts 文件,并将以下代码放入其中。
import { Component, OnInit } from '@angular/core'; import { Http, Headers } from '@angular/http'; import { PercentPipe } from '@angular/common'; import { Router, ActivatedRoute } from '@angular/router'; import { TeamService } from '../../services/teamservice.service' @Component({ templateUrl: './IPLPoll.component.html', }) export class IPLPoll { public teamList: TeamData[]; constructor(public http: Http, private _teamService: TeamService, private _router: Router) { this.getTeamList(); } getTeamList() { this._teamService.getTeams().subscribe( data => this.teamList = data ) } save(team) { this._teamService.saveVotes(team) .subscribe((data) => { this._router.navigate(['/results']); }) } } export class TeamData { teamId: number; teamName: string; voteCount: number; voteShare: number; }
We have created a class TeamData to hold the details of each team, such as teamId, teamName, voteCount and voteShare. Inside our component class IPLPoll , we have created an array variable teamList of type TeamData.
我们创建了一个TeamData类来保存每个团队的详细信息,例如teamId,teamName,voteCount和voteShare。 在组件类IPLPoll中,我们创建了一个数组变量TeamList ,类型为TeamData 。
The getTeamList() method will call the getTeams function of our service TeamService to get the list of teams from the database and assign it to the teamList variable. The getTeamList method is called inside the constructor so that the team data will be displayed as the page loads.
getTeamList()方法将调用我们的服务TeamService的getTeams函数,以从数据库中获取球队列表并将其分配给teamList变量。 在构造函数内部调用getTeamList方法,以便在页面加载时显示团队数据。
The save method will be invoked when the user votes for their favorite team. This will call the saveVotes function of our service to update the vote count of that particular team. The user will then be redirected to the PollResults component to view the poll results.
当用户为自己喜欢的球队投票时,将调用save方法。 这将调用我们服务的saveVotes函数来更新该特定团队的投票计数。 然后,用户将被重定向到PollResults组件以查看轮询结果。
Open the IPLPoll.component.html file and put the following code into it.
打开IPLPoll.component.html 文件,并将以下代码放入其中。
<h1>Who Will Win IPL 2018 ?</h1> <h3>Vote for your favourite team !!! </h3> <hr /> <p *ngIf="!teamList"><em>Loading...</em></p> <table class='table' *ngIf="teamList"> <thead> <tr> <th>Team Name</th> </tr> </thead> <tbody> <tr *ngFor="let team of teamList"> <td>{{ team.teamName }}</td> <td> <button (click)="save(team)" class="btn btn-primary"> Vote <i class="glyphicon glyphicon-thumbs-up"></i></button> </td> </tr> </tbody> </table>
This HTML page will display the list of teams along with a Vote button next to each team. When the user clicks on any of the vote buttons, it will update the vote count and redirect the user to the PollResults page.
该HTML页面将显示团队列表以及每个团队旁边的“ 投票”按钮。 当用户单击任何投票按钮时,它将更新投票计数并将用户重定向到PollResults页面。
Now open the PollResults.component.ts file and put the following code into it.
现在打开PollResults.component.ts 文件,并将以下代码放入其中。
import { Component, OnInit } from '@angular/core'; import { Http, Headers } from '@angular/http'; import { PercentPipe } from '@angular/common'; import { Router, ActivatedRoute } from '@angular/router'; import { TeamData } from '../poll/IPLPoll.component'; import { TeamService } from '../../services/teamservice.service'; import { Observable } from 'rxjs/Observable'; import 'rxjs/add/observable/zip'; import { Chart } from 'angular-highcharts'; @Component({ templateUrl: './PollResult.component.html', }) export class PollResult { public chart: any; public totalVotes: number; public resultList: TeamData[]; constructor(public http: Http, private _teamService: TeamService) { Observable.zip(this._teamService.getTotalVotes(), this._teamService.getTeams()) .subscribe(([totalVoteCount, teamListData]) => { this.totalVotes = totalVoteCount; this.resultList = teamListData; for (let i = 0; i < teamListData.length; i++) { teamListData[i].voteShare = (((teamListData[i].voteCount) / this.totalVotes) * 100); } this.createCharts(); }); } createCharts() { this.chart = new Chart({ chart: { type: 'column' }, title: { text: 'Vote share for each team' }, xAxis: { type: 'category', labels: { rotation: -45, style: { fontSize: '13px', fontFamily: 'Verdana, sans-serif' } } }, yAxis: { min: 0, title: { text: 'Percentage of Votes' } }, legend: { enabled: false }, tooltip: { pointFormat: 'Vote: <b>{point.y:.2f} %</b>' }, series: [{ type: 'column', data: [ { name: this.resultList[0].teamName, y: this.resultList[0].voteShare, color: 'rgba(253, 185, 19, 0.85)' }, { name: this.resultList[1].teamName, y: this.resultList[1].voteShare, color: 'rgba(0, 76, 147, 0.85)' }, { name: this.resultList[2].teamName, y: this.resultList[2].voteShare, color: 'rgba(170, 69, 69, 0.85)' }, { name: this.resultList[3].teamName, y: this.resultList[3].voteShare, color: 'rgba(112, 69, 143, 0.85)' }, { name: this.resultList[4].teamName, y: this.resultList[4].voteShare, color: 'rgba(0, 93, 160, 0.85)' }, { name: this.resultList[5].teamName, y: this.resultList[5].voteShare, color: 'rgba(45, 77, 157, 0.85)' }, { name: this.resultList[6].teamName, y: this.resultList[6].voteShare, color: 'rgba(0, 0, 0, 0.85)' }, { name: this.resultList[7].teamName, y: this.resultList[7].voteShare, color: 'rgba(251, 100, 62, 0.85)' } ], }] }); } }
We are fetching the updated list of team data from the database and the total count of votes for all the teams. We will then calculate the vote share of each team and invoke the createCharts() method to create the chart for the poll results.
我们正在从数据库中获取球队数据的更新列表以及所有球队的总票数。 然后,我们将计算每个团队的投票份额,并调用createCharts()方法为民意调查结果创建图表。
The percentage of vote share for each team is calculated by dividing the vote obtained by each team with the total number of votes. We are doing all these operations in our constructor to display the result as the page loads.
通过将每个团队获得的投票数除以总投票数来计算每个团队的投票份额百分比。 我们正在构造函数中执行所有这些操作,以在页面加载时显示结果。
The createCharts() method will create the column chart with the help of the Highcharts library. The percentage of votes is selected as the Y-axis and the team name is selected as the X-axis. To make things interesting, we are setting the color of each column as the corresponding team jersey color.
createCharts()方法将在Highcharts库的帮助下创建柱形图。 Y轴选择投票百分比,X轴选择团队名称。 为了使事情有趣,我们将每列的颜色设置为相应的队服颜色。
Open the PollResults.component.html file and put the following code into it:
打开PollResults.component.html 文件,并将以下代码放入其中:
<h2>Your vote has been registered successfully !!! </h2> <h3>Here are voting results </h3> <hr /> <p><b>Total votes </b> : {{totalVotes}}</p> <div [chart]="chart"></div>
This HTML page is simple. We are displaying the voting results as a column chart. Just above the chart, we are also displaying the total number of votes.
这个HTML页面很简单。 我们将投票结果显示为柱形图。 在图表上方,我们还显示了投票总数。
Open the /app/app.shared.module.ts file and put the following code into it.
打开/app/app.shared.module.ts文件,并将以下代码放入其中。
import { NgModule } from '@angular/core'; import { CommonModule } from '@angular/common'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { RouterModule } from '@angular/router'; import { ChartModule } from 'angular-highcharts'; import { TeamService } from './services/teamservice.service' import { AppComponent } from './components/app/app.component'; import { NavMenuComponent } from './components/navmenu/navmenu.component'; import { HomeComponent } from './components/home/home.component'; import { IPLPoll } from './components/Poll/IPLPoll.component'; import { PollResult } from './components/Results/PollResult.component'; @NgModule({ declarations: [ AppComponent, NavMenuComponent, HomeComponent, IPLPoll, PollResult ], imports: [ CommonModule, HttpModule, FormsModule, ChartModule, RouterModule.forRoot([ { path: '', redirectTo: 'home', pathMatch: 'full' }, { path: 'home', component: HomeComponent }, { path: 'poll', component: IPLPoll }, { path: 'results', component: PollResult }, { path: '**', redirectTo: 'home' } ]) ], providers: [TeamService] }) export class AppModuleShared { }
Here we have also imported all our components and defined the route for our application as below:
在这里,我们还导入了所有组件,并为我们的应用程序定义了路由,如下所示:
home — which will redirect to the Home component
home-将重定向到Home组件
poll — redirects to the IPLPoll component
poll —重定向到IPLPoll组件
results — redirects to the PollResults component
results —重定向到PollResults组件
Lastly, we need to define the navigation menu for our application. Open the /app/components/navmenu/navmenu.component.html file and put the following code into it:
最后,我们需要为应用程序定义导航菜单。 打开/app/components/navmenu/navmenu.component.html文件,并将以下代码放入其中:
<div class='main-nav'> <div class='navbar navbar-inverse'> <div class='navbar-header'> <button type='button' class='navbar-toggle' data-toggle='collapse' data-target='.navbar-collapse'> <span class='sr-only'>Toggle navigation</span> <span class='icon-bar'></span> <span class='icon-bar'></span> <span class='icon-bar'></span> </button> <a class='navbar-brand' [routerLink]="['/home']">IPLPollDemo</a> </div> <div class='clearfix'></div> <div class='navbar-collapse collapse'> <ul class='nav navbar-nav'> <li [routerLinkActive]="['link-active']"> <a [routerLink]="['/home']"> <span class='glyphicon glyphicon-home'></span> Home </a> </li> <li [routerLinkActive]="['link-active']"> <a [routerLink]="['/poll']"> <span class='glyphicon glyphicon-th-list'></span> Ipl Poll </a> </li> </ul> </div> </div> </div>
And that’s it. We have created our IPL Poll application using Angular 5 and the Entity Framework core.
就是这样。 我们已经使用Angular 5和Entity Framework核心创建了IPL Poll应用程序。
Press F5 to launch the application.
按F5启动应用程序。
A web page will open as shown in the image below. You can see the URL showing the route for our home component, and the navigation menu on the left showing the navigation link for the Ipl Poll page.
如下图所示,将打开一个网页。 您可以看到显示家庭组件路线的URL,以及左侧显示Ipl Poll页面的导航链接的导航菜单。
Click on IPL Poll in the navigaton menu. It will redirect tothe Poll component showing all the team names along with a vote button next to them. Notice the URL has “/Poll” in it.
在导航菜单中单击IPL投票。 它将重定向到显示所有团队名称以及旁边的投票按钮的“投票”组件。 请注意,URL中包含“ / Poll”。
Click on the vote button to vote for your favorite team. You will be redirected to the results page showing the poll results as a column chart.
单击投票按钮为您最喜欢的团队投票。 您将被重定向到结果页面,将轮询结果显示为柱形图。
Since this is the first vote, it is showing 100% for one team and 0% for others. After submitting a few votes for all the teams, we will get the voting results chart as shown below.
由于这是第一票,因此一个团队的投票率为100%,其他团队的投票率为0%。 在为所有团队投票后,我们将获得如下投票结果图表。
We have created an online poll using ASP.NET Core, Angular 5, and the Entity Framework core database first approach with the help of Visual Studio 2017 and SQL Server 2014. We also created a column chart using Highcharts to display the poll results.
我们已经在Visual Studio 2017和SQL Server 2014的帮助下使用ASP.NET Core,Angular 5和Entity Framework核心数据库优先方法创建了一个在线民意调查。我们还使用Highcharts创建了一个柱形图来显示民意调查结果。
Get the source code from Github and play around. Do not forget to put in your own connection string before executing the code.
从Github获取源代码并试用 。 在执行代码之前,请不要忘记输入自己的连接字符串。
You can also find this article at C# Corner.
您也可以在C#Corner上找到此文章。
You can check out my other articles on Angular 5 here
您可以在此处查看有关Angular 5的其他文章
ASP.NET Core — CRUD Using Angular 5 And Entity Framework Core
CRUD Operations With ASP.NET Core Using Angular 5 and ADO.NET
CRUD Operation With ASP.NET Core MVC using Visual Studio Code and ADO.NET
Originally published at ankitsharmablogs.com on May 3, 2018.
最初于2018年5月3日发布在ankitsharmablogs.com上。