使用 node.jsexpressjs 後端開始使用 Angular 2(包括 http 示例)

我們將建立一個簡單的 Hello World! 應用 Angular2 2.4.1(@NgModule 更改)與 node.js(expressjs) 後端。

先決條件

然後執行 npm install -g typescriptyarn global add typescript 以全域性安裝 typescript

路線圖

步驟 1

為我們的應用程式建立一個新資料夾(以及我們後端的根目錄)。我們稱之為 Angular2-express

命令列

mkdir Angular2-express
cd Angular2-express

第 2 步

node.js app 建立 package.json(用於依賴項)和 app.js(用於 bootstrapping)。

package.json:

{
  "name": "Angular2-express",
  "version": "1.0.0",
  "description": "",
  "scripts": {
    "start": "node app.js"
  },
  "author": "",
  "license": "ISC",
  "dependencies": {
    "body-parser": "^1.13.3",
    "express": "^4.13.3"
  }
}

app.js:

var express = require('express');
var app = express();
var server = require('http').Server(app);
var bodyParser = require('body-parser');

server.listen(process.env.PORT || 9999, function(){
    console.log("Server connected. Listening on port: " + (process.env.PORT || 9999));
});

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended: true}) );

app.use( express.static(__dirname + '/front' ) );

app.get('/test', function(req,res){ //example http request receiver
  return res.send(myTestVar);
});

//send the index.html on every page refresh and let angular handle the routing
app.get('/*',  function(req, res, next) {
    console.log("Reloading");
    res.sendFile('index.html', { root: __dirname }); 
});

然後執行 npm installyarn 來安裝依賴項。

現在我們的後端結構已經完成。讓我們繼續前進。

第三步:

我們的前端應該位於 Angular2-express 資料夾中名為 front 的資料夾中。

命令列:

mkdir front
cd front

就像我們對後端一樣,我們的前端也需要依賴檔案。讓我們繼續建立以下檔案:package.jsonsystemjs.config.jstsconfig.json

package.json

{
  "name": "Angular2-express",
  "version": "1.0.0",
  "scripts": {
    "tsc": "tsc",
    "tsc:w": "tsc -w"
  },
  "licenses": [
    {
      "type": "MIT",
      "url": "https://github.com/angular/angular.io/blob/master/LICENSE"
    }
  ],
  "dependencies": {
    "@angular/common": "~2.4.1",
    "@angular/compiler": "~2.4.1",
    "@angular/compiler-cli": "^2.4.1",
    "@angular/core": "~2.4.1",
    "@angular/forms": "~2.4.1",
    "@angular/http": "~2.4.1",
    "@angular/platform-browser": "~2.4.1",
    "@angular/platform-browser-dynamic": "~2.4.1",
    "@angular/platform-server": "^2.4.1",
    "@angular/router": "~3.4.0",
    "core-js": "^2.4.1",
    "reflect-metadata": "^0.1.8",
    "rxjs": "^5.0.2",
    "systemjs": "0.19.40",
    "zone.js": "^0.7.4"
  },
  "devDependencies": {
    "@types/core-js": "^0.9.34",
    "@types/node": "^6.0.45",
    "typescript": "2.0.2"
  }
}

systemjs.config.js:

/**
 * System configuration for Angular samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
  System.config({
    defaultJSExtensions:true,
    paths: {
      // paths serve as alias
      'npm:': 'node_modules/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      app: 'app',
      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
      // other libraries
      'rxjs':                      'npm:rxjs',
      'angular-in-memory-web-api': 'npm:angular-in-memory-web-api',
    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        main: './main.js',
        defaultExtension: 'js'
      },
      rxjs: {
        defaultExtension: 'js'
      }
    }
  });
})(this);

tsconfig.json:

{
  "compilerOptions": {
    "target": "es5",
    "module": "commonjs",
    "moduleResolution": "node",
    "sourceMap": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "removeComments": false,
    "noImplicitAny": false
  },
  "compileOnSave": true,
  "exclude": [
    "node_modules/*"
  ]
}

然後執行 npm installyarn 來安裝依賴項。

現在我們的依賴檔案已經完成了。讓我們繼續我們的節目 17:

index.html 的:

<html>
  <head>
    <base href="/">
    <title>Angular2-express</title>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- 1. Load libraries -->
     <!-- Polyfill(s) for older browsers -->
    <script src="node_modules/core-js/client/shim.min.js"></script>
    <script src="node_modules/zone.js/dist/zone.js"></script>
    <script src="node_modules/reflect-metadata/Reflect.js"></script>
    <script src="node_modules/systemjs/dist/system.src.js"></script>
    <!-- 2. Configure SystemJS -->
    <script src="systemjs.config.js"></script>
    <script>
      System.import('app').catch(function(err){ console.error(err); });
    </script>
    
  </head>
  <!-- 3. Display the application -->
  <body>
    <my-app>Loading...</my-app>
  </body>
</html>

現在我們準備建立我們的第一個元件。在我們的 front 資料夾中建立一個名為 app 的資料夾。

命令列:

mkdir app
cd app

讓我們將以下檔案命名為 main.tsapp.module.tsapp.component.ts

main.ts:

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';

import { AppModule } from './app.module';

const platform = platformBrowserDynamic();
platform.bootstrapModule(AppModule);

app.module.ts:

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { HttpModule } from "@angular/http";

import { AppComponent }   from './app.component';

@NgModule({
  imports:      [ 
    BrowserModule,
    HttpModule    
  ],
  declarations: [ 
    AppComponent
  ],
  providers:[ ],
  bootstrap:    [ AppComponent ]
})
export class AppModule {}

app.component.ts:

import { Component } from '@angular/core';
import { Http } from '@angular/http';

@Component({
  selector: 'my-app',
  template: 'Hello World!',
  providers: []
})
export class AppComponent { 
  constructor(private http: Http){
    //http get example
    this.http.get('/test')
     .subscribe((res)=>{
       console.log(res);
     });
  }
}

在此之後,將 TypeScript 檔案編譯為 javascript 檔案。從當前目錄(Angular2-express 資料夾內)向上移動 2 級並執行以下命令。

命令列:

cd ..
cd ..
tsc -p front

我們的資料夾結構應如下所示:

Angular2-express
├── app.js
├── node_modules
├── package.json
├── front
│   ├── package.json
│   ├── index.html
│   ├── node_modules
│   ├── systemjs.config.js
│   ├── tsconfig.json
│   ├── app
│   │   ├── app.component.ts
│   │   ├── app.component.js.map
│   │   ├── app.component.js
│   │   ├── app.module.ts
│   │   ├── app.module.js.map
│   │   ├── app.module.js
│   │   ├── main.ts
│   │   ├── main.js.map
│   │   ├── main.js

最後,在 Angular2-express 資料夾中,在命令列中執行 node app.js 命令。開啟你最喜歡的瀏覽器並檢視 localhost:9999 以檢視你的應用。