Angular 2 spring события на стороне сервера загрузки
Может кто-нибудь, пожалуйста, предоставит мне пример для событий на стороне сервера w760 > ?
В основном мне нужно переместить события на стороне сервера в браузер. Я использую angular 2 и spring загрузку.
Пожалуйста, предоставьте мне один пример примера, я не могу найти хорошие примеры.
@Controller
public class SSEController {
private final List<SseEmitter> emitters = 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;
}
}
Как непрерывно передавать данные с сервера и как подписаться на это событие в angular 2?
Заранее спасибо
Ответы
Ответ 1
Никто не ответил, поэтому отвечая на мой собственный вопрос.
У вас есть 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;
@RestController
public 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);
});
}
}
Ответ 2
Приведенный выше ответ очень помог.
И..
Чтобы получить реальные данные нажал..
код должен быть
source.onmessage = (message)=>{
let n:Notification = JSON.parse(message.data);
}
source.addEventListener('message', message => {
// There is no data property available on 'message' here
let n: Notification;
n = JSON.parse(message.data);
console.log(message.data);
});
Ответ 3
Ответ от Пратапа А.К. велик. Но чтобы сохранить его немного чище, вы должны создать NotificationService, который реализует интерфейс. Как это:
NotificationServiceImpl.java
public class NotificationServiceImpl implements NotificationService {
public static final List<SseEmitter> emitters = Collections.synchronizedList(new ArrayList<>());
@Override
public SseEmitter initSseEmitters() {
SseEmitter emitter = new SseEmitter();
emitters.add(emitter);
emitter.onCompletion(() -> emitters.remove(emitter));
return emitter;
}
@Override
public void sendSseEventsToUI(WebSource notification) {
List<SseEmitter> sseEmitterListToRemove = new ArrayList<>();
this.emitters.forEach((SseEmitter emitter) -> {
try {
emitter.send(notification, MediaType.APPLICATION_JSON);
} catch (IOException e) {
emitter.complete();
sseEmitterListToRemove.add(emitter);
e.printStackTrace();
}
});
this.emitters.removeAll(sseEmitterListToRemove);
}
}
NotificationService.java
public interface NotificationService {
public SseEmitter initSseEmitters();
public void sendSseEventsToUI(WebSource notification);
}
SSEController.java
@RestController
@RequestMapping("/mystream")
public class SSEController {
@Autowired
NotificationServiceImpl INotificationServiceImpl;
@CrossOrigin
@RequestMapping(path = "/streamsource", method = RequestMethod.GET)
public SseEmitter stream() throws IOException {
return INotificationServiceImpl.initSseEmitters();
}
}
С наилучшими пожеланиями