使用 node.jsexpressjs 后端开始使用 Angular 2(包括 http 示例)
我们将创建一个简单的 Hello World!
应用 Angular2 2.4.1(@NgModule
更改)与 node.js(expressjs)
后端。
先决条件
然后运行 npm install -g typescript
或 yarn 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 install
或 yarn
来安装依赖项。
现在我们的后端结构已经完成。让我们继续前进。
第三步:
我们的前端应该位于 Angular2-express
文件夹中名为 front
的文件夹中。
命令行:
mkdir front
cd front
就像我们对后端一样,我们的前端也需要依赖文件。让我们继续创建以下文件:package.json
,systemjs.config.js
,tsconfig.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 install
或 yarn
来安装依赖项。
现在我们的依赖文件已经完成了。让我们继续我们的节目 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.ts
,app.module.ts
,app.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
以查看你的应用。