|
| 1 | +<template> |
| 2 | + <div> |
| 3 | + <h2>Hub API</h2> |
| 4 | + <form v-on:submit.prevent="addMessage"> |
| 5 | + <input type="text" v-model="newMessage"> |
| 6 | + <input type="submit" value="Send"> |
| 7 | + </form> |
| 8 | + |
| 9 | + <h2>REST API</h2> |
| 10 | + <form v-on:submit.prevent="addRestMessage"> |
| 11 | + <input type="text" v-model="newRestMessage"> |
| 12 | + <input type="submit" value="Send"> |
| 13 | + </form> |
| 14 | + |
| 15 | + <h2>Streaming Hub</h2> |
| 16 | + <form v-on:submit.prevent="countDown"> |
| 17 | + <input type="text" v-model="number"> |
| 18 | + <input type="submit" value="Send"> |
| 19 | + </form> |
| 20 | + |
| 21 | + <ul> |
| 22 | + <li v-for="(message, index) in messages" :key="index">{{message}}</li> |
| 23 | + </ul> |
| 24 | +</div> |
| 25 | +</template> |
| 26 | + |
| 27 | +<script lang="ts"> |
| 28 | +import { HubConnectionBuilder, HubConnection, LogLevel } from "@aspnet/signalr"; |
| 29 | +import { MessagePackHubProtocol } from "@aspnet/signalr-protocol-msgpack"; |
| 30 | +
|
| 31 | +import Vue from "vue"; |
| 32 | +import { Component } from "vue-property-decorator"; |
| 33 | +
|
| 34 | +import { map, filter, switchMap } from 'rxjs/operators'; |
| 35 | +import {adapt} from './stream-adapter'; |
| 36 | +
|
| 37 | +@Component({}) |
| 38 | +export default class MainComponent extends Vue { |
| 39 | + messages: string[] = []; |
| 40 | + newMessage: string = ""; |
| 41 | + newRestMessage: string = ""; |
| 42 | + number: string = ""; |
| 43 | + connection: HubConnection = null; |
| 44 | +
|
| 45 | + created() { |
| 46 | + this.connection = new HubConnectionBuilder() |
| 47 | + .configureLogging(LogLevel.Information) |
| 48 | + .withUrl("/app") |
| 49 | + .withHubProtocol(new MessagePackHubProtocol()) |
| 50 | + .build(); |
| 51 | +
|
| 52 | + console.log(this.connection); |
| 53 | +
|
| 54 | + this.connection.on("Send", message => { |
| 55 | + this.messages.push(message); |
| 56 | + }); |
| 57 | +
|
| 58 | + this.connection.start().catch(error => console.error(error)); |
| 59 | + } |
| 60 | +
|
| 61 | + async addMessage() { |
| 62 | + await this.connection.invoke("Send", { Message: this.newMessage }); |
| 63 | + this.newMessage = null; |
| 64 | + } |
| 65 | + async addRestMessage() { |
| 66 | + await fetch("/message", { |
| 67 | + method: "post", |
| 68 | + body: JSON.stringify({ Message: this.newRestMessage }), |
| 69 | + headers: { |
| 70 | + "content-type": "application/json" |
| 71 | + } |
| 72 | + }); |
| 73 | + this.newRestMessage = null; |
| 74 | + } |
| 75 | +
|
| 76 | + async countDown() { |
| 77 | + var stream = this.connection.stream<string>("CountDown", parseInt(this.number)); |
| 78 | + var messages = this.messages; |
| 79 | + |
| 80 | + adapt(stream).pipe( |
| 81 | + filter(x => parseInt(x) % 2 === 0) |
| 82 | + ).subscribe(x => messages.push(x)); |
| 83 | +
|
| 84 | + this.number = null; |
| 85 | + } |
| 86 | +} |
| 87 | +</script> |
0 commit comments