##服务器通讯 ####Nodejs创建服务器 1、安装typescriptnpm install -g typescript
2、编写tsconfig.json
{
"compilerOptions": {
"outDir": "build",
"module": "commonjs",
"moduleResolution": "node",
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"target": "es5",
"lib": "es6"
},
"exclude": [
"node_modules"
]
}
复制代码
3、编写服务文件hello_server.ts
import * as http from 'http'
const server = http.createServer((request, response) => {
response.end("hello Nodejs!");
});
server.listen(8000);
复制代码
4、编译文件
VScode中: Ctrl+Shift+B
指令编译:tsc XXXXX.ts
5、运行服务node XXXXX.js
*、其他辅助安装npm install express --save
安装express模块,提供简便的服务器功能npm install @types/express --save
声明语法,可以用ts语法调用expressnpm install -g nodemon
安装nodemon,可以监控源码变化,自动重启服务
##http通讯 1、编写proxy.conf.json文件,指定访问地址
{ "/api":{//表明所有的/api的请求都发送到8000去 "target":"http://localhost:8000" } } 2、修改package.json 文件,指定启动项目的时候加载上面的配置文件
"scripts": {
"ng": "ng",
"start": "ng serve --proxy-config proxy.conf.json",
"build": "ng build",
"test": "ng test",
"lint": "ng lint",
复制代码
3、编写调用http服务的代码
export class ProductsComponent implements OnInit {
dataSource: Observable<any>;//声明一个流
products: Array<any> = [];
constructor(private http: Http) {
this.dataSource = this.http.get('/api/products').map((res) => res.json());
}//将response中的流获取出来
ngOnInit() {
this.dataSource.subscribe(//发送请求在这里才触发,而不是构造方法
(data) => this.products = data//监听流,把流里面的数据获取到
);
}
}
复制代码
注意,使用http需要在app里面引用HttpModule
4、编写模板
<div>商品信息</div>
<ul>
<li *ngFor="let product of products" >
{{product.title}}
</li>
</ul>
复制代码
####异步的方式实现 在模板上添加管道
<div>商品信息</div>
<ul>
<li *ngFor="let product of products | async" >
{{product.title}}
</li>
</ul>
复制代码
代码:
products: Observable<any>;//声明一个流
constructor(private http: Http) {
this.products = this.http.get('/api/products').map((res) => res.json());
}
复制代码
##Websocket通讯 这里使用ws项目来进行websocket通讯
1、安装依赖库npm install ws --save
2、安装类型定义文件npm install @types/ws --save-dev
服务器端代码
import { Server } from 'ws';
const wsServer = new Server({ port: 8085 });
wsServer.on("connection", websocket => {
websocket.send("这是服务器主动推送的消息");
websocket.on("message", message => {
console.log("接收到消息:" + message)
})
})
复制代码
客户端服务
import { Observable } from 'rxjs';
import { Injectable } from '@angular/core';
@Injectable()
export class WebSocketService {
ws: WebSocket;
constructor() { }
createObservableSocket(url: string) {
this.ws = new WebSocket(url);
return new Observable(
observer => {
this.ws.onmessage = (event) => observer.next(event.data);
this.ws.onerror = (event) => observer.error(event);
this.ws.onclose = (event) => observer.complete();
}
);
}
sendMessage(message: string) {
this.ws.send(message);
}
}
复制代码
客户端调用socket服务
export class WebSocketComponent implements OnInit {
constructor(private wsService: WebSocketService) { }
ngOnInit() {
this.wsService.createObservableSocket('ws://localhost:8085')
.subscribe(
data => console.log(data),
err => console.log(err),
() => console.log()
);
}
sendMessageToServer() {
this.wsService.sendMessage('这是客户端发送的信息');
}
}复制代码