Angular data15

服务器通讯

  • web服务器搭建
  • http通讯
  • webSocket通讯

1、web服务器

  • 使用Nodejs创建服务器
  • 使用Express创建restFul的httpe服务
  • 监控服务器文件的变化

1.1新建nodeServer文件夹;并运行命令

npm init -y

1.2安装typescript的node的类型安义文件

npm i @types/node --save

1.3新建tsconfig.json文件

{
  /*编译器配置*/
  "compilerOptions": {
    "module": "commonjs",//用的规范
    "target": "es5",//编译成es5
    "emitDecoratorMetadata": true,//编译的时候保留装饰器元数据
    "experimentalDecorators": true,
    "outDir": "build",//编译后放到build目录中去
    "lib": ["es6"] //使用es6语法
  },
  "exclude": [//编译时排除项目
    "node_modules"
  ]
}

1.4 在webstorm中配置


1.5 测试运行node服务器

  • 新建server文件夹和hello_server.ts文件
import * as http from 'http';

const server = http.createServer((request,response)=>{
    response.end('hello Node!');
});
server.listen(8000);
  • 运行编译好的js文件,放在build文件夹中
node build/hello_server.js
  • 为方便开发,安装express框架和express的typescript的类型描述文件
npm install express --save
npm install @types/express --save
  • node服务器运行时不能时时编译,可能安装nodemon来解决这个问题
npm install -g nodemon

安装完成后就可以用nodemon命令来代替node命令来运行服务
如:

nodemon build/hello_server.js

实例 新建auction_server.ts


import * as express from 'express';

const app = express();

/*商品字段定义*/
export class Product {
    constructor(public id: number,
                public title: string,
                public price: number,
                public rating: number,
                public desc: string,
                public categorys: Array<string>) {

    }
}

/*商品的数据*/
const products: Product[] = [
    new Product(1, '商品1', 1.99, 3.5, '第一个商品', ['电子产品', '硬件产品']),
    new Product(2, '商品2', 2.99, 4, '第二个商品', ['电子产品']),
    new Product(3, '商品3', 1.89, 5, '第三个商品', ['图书']),
    new Product(4, '商品4', 1.33, 4.5, '第四个商品', ['电子产品', '硬件产品']),
    new Product(5, '商品5', 3.0, 2.5, '第五个商品', ['硬件产品']),
    new Product(6, '商品6', 4.50, 1.5, '第六个商品', ['电子产品']),
];


app.get('/',(req,res)=>{
    res.send('hello express');
});

//查询商品信息
app.get('/products',(req,res)=>{
    res.json(products);
});

//通过商品id查询
app.get('/product/:id',(req,res)=>{
    res.json(products.find((product) => {
        return product.id == req.params.id
    }))
});

const server = app.listen(8000,"localhost",()=>{
    console.log("服务器启动成功,地址是:http://localhost:8000");
});

运行:

nodemon build/auction_server.js

服务器搭建成功。

http通讯

*angular服务器配置

1、新建proxy.conf.json

{
  "/api":{
    "target":"http://localhost:8000"
  }
}

2、在package.json中修改start命令脚本

"start": "ng serve --proxy-config proxy.conf.json",

这样angular运行的localhost:4200端口请求就会代理到localhost:8000端口上/api路由上

angular的http请求是通过响应式编程的流来实现的

  • 一种是组件中的Observable流通过subscribe来发射http请求;

结合上面搭建的http服务器,

ng new client 命令生成一个项目;
ng g component product 命令生成product组件;

  • product.component.ts代码
import { Component, OnInit } from '@angular/core';
import {Observable} from "rxjs/Observable";
import {Http} from "@angular/http";
import 'rxjs/Rx';

@Component({
  selector: 'app-product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {

  //定义数据流
  dataSource:Observable<any>;
  //与模块数据绑定的数组
  products:Array<any>=[];

  constructor(private http:Http) {
    /*
    *get方法返回的数据流是response数据类型,要用json方法转换成json格式;
    * 作用map方法,需要import 'rxjs/Rx'
    * */

    this.dataSource = this.http.get('/api/products')
      .map((res)=>res.json());
  }

  ngOnInit() {
    /*
    * dataSource数据流通过订阅subscribe把data传给this.products做模板绑定
    * */
    this.dataSource.subscribe(
      (data)=>this.products = data
      );
  }
}

product.component.html代码:

<div>
  商品信息
</div>
<ul>
  <li *ngFor="let product of products">
    {{product.title}}
  </li>
</ul>
  • 一种是通过管道命令async在模板中自动的订阅一个流;
    代码重构后如下:
  • product.component.ts中
import { Component, OnInit } from '@angular/core';
import {Observable} from "rxjs/Observable";
import {Headers, Http} from "@angular/http";
import 'rxjs/Rx';

@Component({
  selector: 'app-product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {


  //模板中通过管道async自动订阅了products流
  products:Observable<any>;

  constructor(private http:Http) {
    //增加请求头信息
    let myHeaders:Headers = new Headers();
    myHeaders.append('Authorization',"Basic 123456");
    this.products = this.http.get('/api/products',{headers:myHeaders})
      .map((res)=>res.json());
  }

  ngOnInit() {
  }

}
  • product.component.html中
<div>
  商品信息
</div>
<ul>
  <li *ngFor="let product of products | async">
    {{product.title}}
  </li>
</ul>

Websocket协议

Websocket是个长连接,可以在接收数据的同时发送数据。

  • 接上上面的nodejs搭建的server的例子;我们用ws来实现一个Websocket的服务器
npm install ws --save
npm install @types/ws --save

在client这个项目中新建个service

ng g service shared/webSocket
  • web-socket.service.ts代码
import {Injectable} from '@angular/core';
import {Observable} from "rxjs/Observable";
import 'rxjs/Rx';

@Injectable()
export class WebSocketService {

  //定义一个WebSocket类型的属性
  ws: WebSocket;

  constructor() {
  }


//创建一个websocket的流
  createObservableSocket(url: string): Observable<any> {
    //开始WebSocket连拉
    this.ws = new WebSocket(url);
    /*
    * 返回一个定义的流
    * 1、什么时候发躲一个元素
    * 2、什么时候抛一个异常
    * 3、什么时候发出流结束的信号
    * */
    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);
  }

}

新建一个webSocket组件

ng g component webSocket

通过一个按扭给服务器发送消息

  • web-socket.component.ts组件代码
import { Component, OnInit } from '@angular/core';
import {WebSocketService} from "../shared/web-socket.service";

@Component({
  selector: 'app-web-socket',
  templateUrl: './web-socket.component.html',
  styleUrls: ['./web-socket.component.css']
})
export class WebSocketComponent implements OnInit {

  constructor(private wsServer:WebSocketService) { }

  ngOnInit() {
    //订阅webSocket的流
    this.wsServer.createObservableSocket("ws://localhost:8085")
      .subscribe(
        data =>console.log(data),
        err =>console.log(err),
        ()=>console.log('流已经结束')
      );
  }
  sendMessageToServer(){
    this.wsServer.sendMessage('Hello form client!');
  }

}

  • web-socket.component.html模板代码
<button (click)="sendMessageToServer()">向服务器发消息!</button>
  • 定义一个创建流格式的服务
    web-socket.service.ts代码
import {Injectable} from '@angular/core';
import {Observable} from "rxjs/Observable";
import 'rxjs/Rx';

@Injectable()
export class WebSocketService {

  //定义一个WebSocket类型的属性
  ws: WebSocket;

  constructor() {
  }

//创建一个websocket的流
  createObservableSocket(url: string): Observable<any> {
    //开始WebSocket连拉
    this.ws = new WebSocket(url);
    /*
    * 返回一个定义的流
    * 1、什么时候发躲一个元素
    * 2、什么时候抛一个异常
    * 3、什么时候发出流结束的信号
    * */
    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);
  }
}

service中只是定义流,只有在组件中注入后,用subscribe订阅后,才会产生流。

  • http服务器端代码
    auction_server.ts

import * as express from 'express';

import { Server } from 'ws';

const app = express();

/*商品字段定义*/
export class Product {
    constructor(public id: number,
                public title: string,
                public price: number,
                public rating: number,
                public desc: string,
                public categorys: Array<string>) {

    }
}

/*商品的数据*/
const products: Product[] = [
    new Product(1, '商品1', 1.99, 3.5, '第一个商品', ['电子产品', '硬件产品']),
    new Product(2, '商品2', 2.99, 4, '第二个商品', ['电子产品']),
    new Product(3, '商品3', 1.89, 5, '第三个商品', ['图书']),
    new Product(4, '商品4', 1.33, 4.5, '第四个商品', ['电子产品', '硬件产品']),
    new Product(5, '商品5', 3.0, 2.5, '第五个商品', ['硬件产品']),
    new Product(6, '商品6', 4.50, 1.5, '第六个商品', ['电子产品']),
];


app.get('/',(req,res)=>{
    res.send('hello express');
});

//查询商品信息
app.get('/api/products',(req,res)=>{
    res.json(products);
});

//通过商品id查询
app.get('/api/product/:id',(req,res)=>{
    res.json(products.find((product) => {
        return product.id == req.params.id
    }))
});

const server = app.listen(8000,"localhost",()=>{
    console.log("服务器启动成功,地址是:http://localhost:8000");
});

//new ws的Server对象
const wsServer = new Server({port:8085});
//当websocket连接成功后,服务器主动推送的数据
wsServer.on('connection',websocket =>{
    //连接上服务器,推送消息
    websocket.send('这是服务器主动推送的消息');
    //接收到消息,打印到控制台上。
    websocket.on('message',message =>{
        console.log('接收到消息是:'+message);
    })
});

//设置定时推送消息
setInterval(()=>{
    //如果有客户端连接上来
    if(wsServer.clients){
        wsServer.clients.forEach(client => {
            client.send('这是定时推送的消息');
        })
    }
},2000)

源码1 nodeServer 链接:http://pan.baidu.com/s/1dFniw8p 密码:elap
源码2 client 链接:http://pan.baidu.com/s/1i5ckS5n 密码:fbw2

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 194,524评论 5 460
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 81,869评论 2 371
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 141,813评论 0 320
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 52,210评论 1 263
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 61,085评论 4 355
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 46,117评论 1 272
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 36,533评论 3 381
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 35,219评论 0 253
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 39,487评论 1 290
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 34,582评论 2 309
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 36,362评论 1 326
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 32,218评论 3 312
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 37,589评论 3 299
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 28,899评论 0 17
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 30,176评论 1 250
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 41,503评论 2 341
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 40,707评论 2 335

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,497评论 18 139
  • Spring Boot 参考指南 介绍 转载自:https://www.gitbook.com/book/qbgb...
    毛宇鹏阅读 46,679评论 6 342
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 171,057评论 25 707
  • 其实,我只是害怕,害怕你对我好之后却没有完美的结局,也害怕你不对我好之后消失的爱情
    昵称已存在阅读 164评论 0 0
  • 游完壶口,夜宿宜川。宜昌、宜川,一个‘‘宜’’字,顿生亲近之感,想必一定有宜人之处,也一定是宜居之地。宜川属延安...
    杨新华_edf7阅读 267评论 0 1