Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import {Inject, Injectable} from "@angular/core";
- import { StompService } from 'ng2-stomp-service';
- import { Storage } from '@ionic/storage';
- import {APP_CONFIG, IAppConfig} from "../app/app.config";
- import {ChatMessage} from "../models/chat-message";
- @Injectable()
- export class WebsocketService {
- private subscription : any;
- private websocketApi:string;
- constructor(@Inject(APP_CONFIG) private config: IAppConfig, private storage: Storage, private stomp: StompService){
- this.websocketApi = this.config.apiEndpoint;
- console.log(storage);
- this.storage.get('jwt_token').then((token)=>{
- if (token !== null){
- // this.ws = io(this.websocketApi + 'chat', {
- // extraHeaders: {
- // Authorization: "Bearer "+ token
- // }
- // });
- console.log(token)
- this.initWebsock(token);
- }
- });
- }
- initWebsock(auth_token:string) {
- //configuration
- let headers: StompHeaders;
- this.stomp.configure({
- host:this.websocketApi + 'chat',
- queue:{'init':false},
- headers: {
- Authentication: `Bearer ${auth_token}`
- },
- });
- //start connection
- this.stomp.startConnect().then(() => {
- this.stomp.done('init');
- console.log('connected');
- //subscribe
- this.subscription = this.stomp.subscribe('/topic/messages', this.response);
- //send data
- this.stomp.send('/topic/messages',{"data":"sample_data"});
- //unsubscribe
- this.subscription.unsubscribe();
- //disconnect
- this.stomp.disconnect().then(() => {
- console.log( 'Connection closed' )
- });
- });
- }
- public response = (data) => {
- console.log(data)
- }
- unsubscribe() {
- this.subscription.unsubscribe();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement