栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

Angular 2 Spring Boot服务器端事件

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Angular 2 Spring Boot服务器端事件

没有人回答,所以回答我自己的问题。

有一个Spring Rest控制器

SseController.java

import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestMethod;import org.springframework.web.bind.annotation.RestController;import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;import java.io.IOException;import java.util.ArrayList;import java.util.Collections;import java.util.List;@RestControllerpublic class SSEController {    public static final List<SseEmitter> emitters = Collections.synchronizedList( new ArrayList<>());    @RequestMapping(path = "/stream", method = RequestMethod.GET)    public SseEmitter stream() throws IOException {        SseEmitter emitter = new SseEmitter();        emitters.add(emitter);        emitter.onCompletion(() -> emitters.remove(emitter));        return emitter;    }}

ServiceClass.java

public void sendSseEventsToUI(Notification notification) { //your model class        List<SseEmitter> sseEmitterListToRemove = new ArrayList<>();        SSEController.emitters.forEach((SseEmitter emitter) -> { try {     emitter.send(notification, MediaType.APPLICATION_JSON); } catch (IOException e) {     emitter.complete();     sseEmitterListToRemove.add(emitter);     e.printStackTrace(); }        });        SSEController.emitters.removeAll(sseEmitterListToRemove);    }

最后在Angular2组件中执行此操作

notification.component.ts

import {Component, OnInit} from '@angular/core';declare let EventSource:any;@Component({    selector: 'notification-cmp',    templateUrl: 'notification.component.html'  })export class NotificationComponent implements onInit {   connect(): void {        let source = new EventSource('http://localhost:8080/stream');        source.addEventListener('message', message => { let n: Notification; //need to have this Notification model class in angular2 n = JSON.parse(message.data); console.log(message.data);         });    }}


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/408560.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号