ASP.Net Core API + Angular 2 + TypeScript





5.00/5 (1投票)
使用 TypeScript 集成 ASP.Net Core API 与 Angular 2
引言
有很多方法可以创建一个将 ASP.NET Core 1.0 API 与 Angular 2 集成的项目。上周我为此挣扎了很多。该项目有很多冲突,不易于使用,并且 webpack 非常复杂。随着项目越来越大,使用起来变得非常缓慢,而且如果你想更改任何 TypeScript 文件,你必须编译整个项目。
我决定创建自己的方法。我创建了两个独立的工程:ASP.NET Core 工程,使用 VS2017 开发;另一个是 Angular 工程,使用 Visual Studio Code 开发,它速度很快,并且可以实时编译。
背景
你需要 Nodejs、TypeScript、Visual Studio 2017 和 Visual Studio Code
使用代码
创建一个 ASP.NET Core 项目。一个直接的项目,包含演示类
运行该项目。它将使用 localhost 和一个端口运行。
这是我们将在 Angular 项目中调用的函数。
//
[Route("api/[controller]")]
public class ValuesController : Controller
{
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
//
现在我们想要创建 Angular 项目
要安装 CLI,我们将使用 Node 和 npm
<code>npm install -g angular-cli</code>
进入项目目录
要启动一个新的应用程序,只需运行命令
<code>ng new ProjectName</code>
打开 Visual Studio Code
打开 Angular 项目的文件夹并更新 app.components.ts
//
import { Component } from '@angular/core';
import { Http } from '@angular/http';
import {globalVariables} from "./globals";
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
values :string [];
title = 'app works!';
v :any ;
constructor(http: Http) {
http.get(globalVariables.apiurl + '/api/values').subscribe(result => {
this.values=result.json()
this.title += " -> " + this.values[0] +"," + this.values[1] ;
console.log(this.values);
});
}
}
//
我创建了一个全局变量类 "service" 来包含 API URL 的值,因为它将在许多地方使用,并且可以在发布过程中更改。
全局变量:globals.ts
export let globalVariables = {
AppName:"test",
apiurl: "https://:50434", // the api url
};
//
它正在工作
需要注意的点
- 这两个项目托管在不同的端口上,这就是为什么我们需要 Angular 项目中 API URL 路径的常量。
- 在发布时,这两个项目将被合并,因此常量可以为空。
- Chrome 会阻止你跨越两个 URL 之间的 URL,因此你需要这个扩展程序:https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi/related?hl=en-US
关注点
我创建这个作为一个概念验证。这只是开始创建你自己的项目,我在使用合并这两个项目的整个模板时学到了很多。
历史
在此处保持您所做的任何更改或改进的实时更新。