如何在角度6中使用套接字服务?

时间:2018-07-19 11:57:02

标签: javascript angular sockets socket.io

我是套接字新手,所以我要在angular 6项目中实现套接字服务。.

如何在Angular 6中使用套接字?

可能正在使用一些很酷的Socket示例?

图书馆?教程?博客文章?

1 个答案:

答案 0 :(得分:4)

如何在角度6中使用套接字服务?

1。首先,您必须以类似的角度创建组件:

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。您必须创建以下服务:

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;
        });
    }
}