Single Page Web Application
一:源起 ~~~
單頁面應用,其實互聯網一開始就是這個,只不過後來內容多了導致一個頁面實在影響用戶體驗得變爲多頁面,然後就是當時沒有ajax以及頁面模板單頁面切換的概念(主要是沒ajax從而沒順勢想到單頁切換)。然後Angular來了,React隨後跟進,Vue也順勢來湊一波熱鬧,然後。。。咳咳,今天主要講.net core 結合 angular做出來的spa。
二:SPA創建 ~~~
開發環境:
vs 2017(15.7.5) (可選)
angular (v 6.0.9) (必須)
node(v 8.11.3) (可選)
npm (v 5.6.0) (可選)
angular CLI (v 6.0.8) (必須)
搬磚實錄:
創建 asp.net core web 應用程序(這裏我選空模板,當然你可以選其他,這個就看你自己的喜好了,步驟都差不多,可以跳着看)創建完的大致目錄結構如下:
可以看出這是一個多麼簡潔的結構,也是我一直喜歡的風格,直到angular那一大坨東西的創建,下面可以看出,所以angular這種越往後,越後端的風格以及採用typescript這種格式語言,雖然身爲後端出身的我看起來無比熟悉,但是實在喜歡不上,反而之前看不順眼的JavaScript反倒是親切多了,這可能就是那句物極必反以及喜新厭舊以及反覆無常的綜合徵吧。
創建angular的項目工程,首先你得打開cmd(要是你用的是Visio stodio或者是webstore的就不需要這麼幹了,當然也就不會像我這樣先創建.net core 再去搞這個,原諒我是一個.net從業員的思維)。cmd 命令如下:
F: //切換盤符 cd F:\VS2017Project\AG //導向到你當前的工程目錄 ng new AG //新建angular的工程目錄(AG爲我自定義的目錄)
創建完成後目錄是這樣子的:
3. 修改Startup.cs
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.AspNetCore.Http; using Microsoft.Extensions.DependencyInjection; //這個是導入SPA服務的關鍵dll using Microsoft.AspNetCore.SpaServices.AngularCli; namespace AG { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 public void ConfigureServices(IServiceCollection services) { //註冊SPA服務 services.AddSpaStaticFiles(configuration => { //設置你對應的angular項目配置文件名 configuration.RootPath = "AG/dist"; }); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { //調用SPA服務 app.UseSpa(spa => { // To learn more about options for serving an Angular SPA from ASP.NET Core, // see https://go.microsoft.com/fwlink/?linkid=864501 //設置你對應的angular項目文件名 spa.Options.SourcePath = "AG"; if (env.IsDevelopment()) { //這裏就是去調用了ng的start命令去啓動這個angular項目 spa.UseAngularCliServer(npmScript: "start"); } else { app.UseExceptionHandler("/Error"); app.UseHsts(); } }); } } }
主要是SPA服務的引入,其他的暫時不需要,目前也只是這個angular項目簡單掛起的demo,啓動項目,運行如下:
三:預知後事如何,請看下回分解(創建一個智能家居物聯的SPA應用)