How to use socket service in angular 6?
1.First you have to create component in angular like :
socketComponent.ts
import { SocketDataService } from 'socketDataService';
import { Subscription } from 'rxjs';
@Component({
selector: 'app-socket',
templateUrl: './app-socket.component.html',
styleUrls: ['./app-socket.component.css'],
})
export class SocketComponent implements OnInit {
sub: Subscription;
constructor(private socketDataService: SocketDataService) {}
ngOnInit() {
this.getSocketData();
}
getSocketData(): void {
this.sub = this.socketDataService.getSocketData()
.subscribe(data => {
this.socketData = data
})
}
}
2. You have to create service like :
socketService.ts
import { Observable } from 'rxjs/Observable';
@Injectable()
export class SocketDataService {
private socket;
constructor(private http: Http) {
this.socket = io('http://localhost:3000')
}
observer
getSocketData(): Observable<any> {
this.socket.on('socket-data', (res) => {
this.observer.next(res);
});
return this.getSocketDataObservable();
}
getSocketDataObservable(): Observable<any> {
return new Observable(observer => {
this.observer = observer;
});
}
}