Angular学习笔记08——连接

##服务器通讯 ####Nodejs创建服务器 1、安装typescript
npm 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语法调用express
npm 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('这是客户端发送的信息');
  }

}复制代码

转载于:https://juejin.im/post/5a2df1646fb9a045170523e6

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值