Advertisement
Guest User

Untitled

a guest
Oct 20th, 2017
83
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.79 KB | None | 0 0
  1. import {Inject, Injectable} from "@angular/core";
  2. import { StompService } from 'ng2-stomp-service';
  3. import { Storage } from '@ionic/storage';
  4. import {APP_CONFIG, IAppConfig} from "../app/app.config";
  5. import {ChatMessage} from "../models/chat-message";
  6.  
  7.  
  8. @Injectable()
  9. export class WebsocketService {
  10. private subscription : any;
  11.  
  12. private websocketApi:string;
  13.  
  14.  
  15. constructor(@Inject(APP_CONFIG) private config: IAppConfig, private storage: Storage, private stomp: StompService){
  16. this.websocketApi = this.config.apiEndpoint;
  17.  
  18. console.log(storage);
  19. this.storage.get('jwt_token').then((token)=>{
  20. if (token !== null){
  21. // this.ws = io(this.websocketApi + 'chat', {
  22. // extraHeaders: {
  23. // Authorization: "Bearer "+ token
  24. // }
  25. // });
  26. console.log(token)
  27. this.initWebsock(token);
  28. }
  29. });
  30. }
  31.  
  32.  
  33. initWebsock(auth_token:string) {
  34. //configuration
  35. let headers: StompHeaders;
  36.  
  37. this.stomp.configure({
  38. host:this.websocketApi + 'chat',
  39.  
  40. queue:{'init':false},
  41. headers: {
  42. Authentication: `Bearer ${auth_token}`
  43. },
  44. });
  45.  
  46. //start connection
  47. this.stomp.startConnect().then(() => {
  48. this.stomp.done('init');
  49. console.log('connected');
  50.  
  51. //subscribe
  52. this.subscription = this.stomp.subscribe('/topic/messages', this.response);
  53.  
  54. //send data
  55. this.stomp.send('/topic/messages',{"data":"sample_data"});
  56.  
  57. //unsubscribe
  58. this.subscription.unsubscribe();
  59.  
  60. //disconnect
  61. this.stomp.disconnect().then(() => {
  62. console.log( 'Connection closed' )
  63. });
  64. });
  65. }
  66.  
  67. public response = (data) => {
  68. console.log(data)
  69. }
  70.  
  71. unsubscribe() {
  72. this.subscription.unsubscribe();
  73. }
  74. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement