Angular与服务器通讯

创建Web服务器

使用Nodejs创建服务器

使用typescript语言开发服务器
配置开发环境
1.
–> npm init -y
初始化文件夹,-y:建立包含默认配置的package.json文件
2.
–> npm i @types/node --save
引入node的类型定义文件
类型定义文件:让开发者在typescript中使用已有的javascript写成的库
3.
node本身不认typescript,将typescript编译为javascript
–> new tsconfig.json

/*编译器如何将typescript编译为javascript*/
{
  "compilerOptions":{//编译器的配置
    "target": "es5",//目标es5规范的脚本
    "module": "commonjs",
    "emitDecoratorMetadata": true, //装饰器相关
    "experimentalDecorators": true,//装饰器相关
    "outDir": "build",//编译完放build的文件里
    "lib": ["es6"]//开发使用es6的语法
  },
  "exclude": [//排除
    "node_modules"//第三方的包
  ]
}

在这里插入图片描述
使用此配置文件作为配置来编译typescript
在这里插入图片描述
创建服务器
在这里插入图片描述

import * as http from 'http'
const server = http.createServer((request, response) => {
    response.end("hello Node!");
})
server.listen(8000);

启动服务器
–> node build/help_server.js
在这里插入图片描述

使用Express创建restful的http服务

===
1.
–> npm install express --save
在原始node上开发需要手工处理很多问题:读取文件,路由请求,处理各种请求类型
简化开发,减少手工编码量,安装Express框架
2.
–> npm install @types/express --save
引入Express的类型定义文件
3.

import * as express from 'express'
/*app :声明服务器端提供的http服务的*/
const app = express();
app.get('/',(req, res) => {
   res.send("Hello Express!")
});
app.get('/products',(req, res) => {
    res.send("接收到商品查询请求!")
});
const server = app.listen(8000,"localhost",() => {
    console.log("服务器已经启动,地址是:http://localhost:8000");
});

在这里插入图片描述
启动服务器
–> node build/auction_server.js
在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
4.

import * as express from 'express'
/*app :声明服务器端提供的http服务的*/
const app = express();
app.get('/',(req, res) => {
   res.send("Hello Express!")
});
app.get('/products',(req, res) => {
    res.send("接收到商品查询请求!!!")
});
const server = app.listen(8000,"localhost",() => {
    console.log("服务器已经启动,地址是:http://localhost:8000");
});

在这里插入图片描述
停止:ctrl+shift+c
重启:–> node build/auction_server.js
在这里插入图片描述

监控服务器文件的变化

===
1.
–> npm install -g nodemon
监控源代码,改变时自动重启服务器,并加载最新的代码
2.
–> nodemon build/auction_server.js

在线竞拍商品
import * as express from 'express'
/*app :声明服务器端提供的http服务的*/
const app = express();
export class Product {
    constructor(
        public id: number,
        public title: string,
        public price: number,
        public rating: number,
        public desc: string,
        public categories: Array<string>
    ) {
    }
}
const products: Product[] = [
    new Product(1, '第一个商品', 1.99, 2.5, '这是第一个商品', ['电子产品', '硬件设备']),
    new Product(2, '第二个商品', 2.99, 3.5, '这是第二个商品', ['图书']),
    new Product(3, '第三个商品', 3.99, 4.5, '这是第三个商品', ['硬件设备']),
    new Product(4, '第四个商品', 4.99, 3.5, '这是第四个商品', ['电子产品', '硬件设备']),
    new Product(5, '第五个商品', 5.99, 2.5, '这是第五个商品', ['电子产品']),
    new Product(6, '第六个商品', 6.99, 3.5, '这是第六个商品', ['图书'])
];
app.get('/',(req, res) => {
   res.send("Hello Express!")
});
app.get('/products',(req, res) => {
    res.json(products)
});
app.get('/product/:id',(req, res) => {
    res.json(products.find((product) => product.id == req.params.id))
});
const server = app.listen(8000,"localhost",() => {
    console.log("服务器已经启动,地址是:http://localhost:8000");
});

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述

Http通讯

了解angular的http服务
发送http请求
处理http响应

look this :https://majing.io/posts/10000020421171
app.module.ts

import {HttpClientModule} from '@angular/common/http';
...
  imports: [
    HttpClientModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

proxy.conf.json

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

package.json start

{
  "name": "demo1",
  "version": "0.0.0",
  "scripts": {
    "ng": "ng",
    "start": "ng serve --proxy-config proxy.conf.json",
    "build": "ng build",
    "test": "ng test",
    "lint": "ng lint",
    "e2e": "ng e2e"
  },
  ...

product.component.ts

import { Component, OnInit } from '@angular/core';
import {Observable} from 'rxjs/index';
/*import { map } from 'rxjs/operators';*/
import { HttpClient } from '@angular/common/http';
@Component({
  selector: 'app-product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {
  /*Observable:响应式编程的流,接收http服务返回的流*/
  dataSource: Observable<any>;
  /*和模板数据绑定*/
  products: Array<any> = [];
  constructor(private http: HttpClient) {
    /*this.dataSource = this.http.get('/api/products').pipe(map(res => (<Response>res).json()));*/
    this.dataSource = this.http.get('/api/products');
  }
  ngOnInit() {
    /*订阅到的数据传给products属性*/
    this.dataSource.subscribe((data) => this.products = data);
  }
}

product.component.html

<div>商品信息</div>
<ul>
  <li *ngFor="let product of products">{{product.title}}</li>
</ul>

app.component.html

<app-product></app-product>

在这里插入图片描述
在这里插入图片描述
在这里插入图片描述
product.component.ts

import { Component, OnInit } from '@angular/core';
import {Observable} from 'rxjs/index';
import { HttpClient } from '@angular/common/http';
@Component({
  selector: 'app-product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {
  /*Observable:响应式编程的流,接收http服务返回的流*/
  products:: Observable<any>;
  constructor(private http: HttpClient) {
    this.products: = this.http.get('/api/products');
  }
  ngOnInit() {
  }
}

product.component.html

<div>商品信息</div>
<ul>
  <!--async管道:接收流作为参数,自动订阅流-->
  <li *ngFor="let product of products | async">{{product.title}}</li>
</ul>

angular:httpclient设置header
product.component.ts

import { Component, OnInit } from '@angular/core';
import {Observable} from 'rxjs/index';
import { HttpClient } from '@angular/common/http';
@Component({
  selector: 'app-product',
  templateUrl: './product.component.html',
  styleUrls: ['./product.component.css']
})
export class ProductComponent implements OnInit {
  /*Observable:响应式编程的流,接收http服务返回的流*/
  products:: Observable<any>;
  constructor(private http: HttpClient) {
   	const myHeaders = new HttpHeaders().set('Authorization', 'Basic 123456');
    this.products = this.http.get('/api/products', {headers: myHeaders});
  }
  ngOnInit() {
  }
}

在这里插入图片描述

WebSocket通讯

了解WebSocket协议
创建WebSocket服务器
使用WebSocket协议通讯

在这里插入图片描述
在这里插入图片描述
1.
安装ws
–> npm install ws --save
类型定义文件
–> npm install @types/ws --save-dev
在这里插入图片描述
2.

/**
 * Created by Administrator on 2019/1/4/004.
 */
import * as express from 'express'
import {Server} from "ws";
...
const wsServer = new Server({port:8085});
wsServer.on("connection",websocket => {
    websocket.send("这个消息是服务器主动推送的");
})

在这里插入图片描述
2. 生成服务
–> ng g service shared/webSocket
web-socket.service.ts

import { Injectable } from '@angular/core';
import {Observable} from 'rxjs/index';
@Injectable({
 providedIn: 'root'
})
export class WebSocketService {
 ws: WebSocket;
 constructor() { }
 createObservableSocket(url: string): Observable<any> {
   this.ws = new WebSocket(url);
   return new Observable(
     observable => {
       this.ws.onmessage = (event) => observable.next(event.data);
       this.ws.onerror = (event) => observable.error(event);
       this.ws.onclose = (event) => observable.complete();
     }
   );
 }
 sendMessage(message: string) {
   this.ws.send(message);
 }
}
  1. 生成组件
    –> ng g component web-socket
    app.module.ts 声明提供器
...
 providers: [WebSocketService],
...
})
export class AppModule { }

web-socket.service.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 wsService: WebSocketService) { }

 ngOnInit() {
   /*订阅服务的方法的返回的流*/
   this.wsService.createObservableSocket('ws://localhost:8085')/*ws:webSocket协议*/
     .subscribe(
       data => console.log(data),
       err => console.log(err),
       () => console.log('流已经结束!')
     );
 }
 sendMessageToServer() {
   this.wsService.sendMessage('hello from client!');
 }
}

在这里插入图片描述

/*定时推送*/
setInterval(() => {
    if(wsServer.clients){
        wsServer.clients.forEach(client => {
            client.send("这是定时推送");
        })
    }
},2000);
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值