多次使用Websocket订阅呼叫?

时间:2018-10-20 10:01:07

标签: angular websocket rxjs angular6 subscribe

我的Web-socket-service.ts

import { Injectable } from '@angular/core';
import { OidcSecurityService } from 'angular-auth-oidc-client';
import { WebSocketSubject } from 'rxjs/observable/dom/WebSocketSubject';
import { environment } from './../../../environments/environment';



export class Headers {
  public name = 'Authorization';
  public value = 'Bearer ';
}


export class Request {
  public id: string;
  public method = 'GET';
  public path = 'EmployeeList/';
  public dataFormat = 'application/json';
  public headers: Headers;
  public data: Data;
  constructor(
    id,
    method,
    path,
    dataFormat,
    headers
  ) {
    this.id = id;
    this.method = method;
    this.path = path;
    this.dataFormat = dataFormat;
    this.headers = headers;
  }

}
@Injectable({
  providedIn: 'root'
})
export class WebSocketService {
  public serverMessages = new Array<Request>();
  public id = 12;
  public method = 'GET';
  public path = 'EmployeeList/';
  public dataFormat = 'application/json';
  public headers: Headers;
  public headersArray: Headers[]


  private socket$: WebSocketSubject<Request>;

  constructor(private oidcSecurityService: OidcSecurityService) {
    this.socket$ = new WebSocketSubject('url');
    this.headers = new Headers();
    this.headersArray =[];

    this.headers.value = this.headers.value.concat(this.oidcSecurityService.getToken());
    this.headersArray.push(this.headers);
    this.headersArray.push({name : 'request_id',value : Math.round (Date.now()/1000).toString()})

  }

  GetData() {
    debugger;
    this.path = 'EmployeeList/';
    const message = new Request(this.id, 'GET', this.path, this.dataFormat,  this.headersArray);
    console.log(message);
    message.data = null;
   this.socket$.next(message);
    return this.socket$;
  }

  InsertData(newData) {
    const message = new Request('', 'POST', this.path, this.dataFormat, this.headers);
    message.data = newData;
    this.socket$.next(message);
    return this.socket$;
  }
  UpdateData(SimData) {
    const message = new Request('', 'PUT', this.path, this.dataFormat, this.headers);
    message.data = SimData;
    this.socket$.next(message);
    return this.socket$;
  }
  DeleteDatabyID(Id) {
    this.path = `${'EmployeeList'}/${Id}`;
    const message = new Request(Id, 'Delete', this.path, '', this.headers);
    message.data = null;
    this.socket$.next(message);
    return this.socket$;
  }


  GetEmployeeReportData() {
    this.path = 'EmployeeReports/';
    const message = new Request(this.id, 'GET', this.path, this.dataFormat, this.headers);
    message.data = null;
    this.socket$.next(message);
    return this.socket$;
     }
    }

我的employeeListComponent.ts

import { Component, OnInit, ChangeDetectorRef } from "@angular/core";
import { MatSnackBar } from "@angular/material";

import {
  FormGroup,
  FormBuilder,
  FormControl,
  FormArray,
  Validators
} from "@angular/forms";
import "rxjs/add/operator/map";
import "rxjs/add/operator/toPromise";
import { MatDialog, MatDialogRef, MAT_DIALOG_DATA } from "@angular/material";
import { OidcSecurityService } from "angular-auth-oidc-client";
import { Subscription } from "rxjs/Subscription";
import { WebSocketService } from "./../../core/services/web-socket.service";
import { Data } from "./../../core/services/web-socket.service";
import { DeleteComponent } from "./../delete/delete.component";



@Component({
  selector: "app-simulator",
  templateUrl: "./employeeList.component.html",
  styleUrls: ["./employeeList.component.scss"]
})

export class employeeListComponent implements OnInit {
  emplist;

  constructor(
    private socketService: WebSocketService,
    private oidcSecurityService: OidcSecurityService,
    private fb: FormBuilder,
    public snackBar: MatSnackBar,
    private changeDetect: ChangeDetectorRef,
    public dialog: MatDialog,

  ) {


  }

  ngOnInit() {

    this.GetemployeeList();

  }

  GetemployeeList() {
    this.socketService.GetData().subscribe(
      response => {
       this.emplist= response;
      },
      error => console.log(error)
    );
    this.changeDetect.detectChanges();
  }


  InsertEmployee() {
    let data = new Data();
    // data.name = "abc"
       ......

    this.socketService.InsertData(data).subscribe(
      () => {
        this.snackBar.open("employee Added Successfully!", "Success", {
          duration: 2000,
          verticalPosition: "top"
        });
      },
      error => console.log(error)
    );
    this.aviatorForm.reset();
    data = null;
  }

  UploadEmployee(empdata,id) {
    let data = new Data();
   // data.name = empdata.name
     .....
    this.socketService.UpdateData(data).subscribe(() => {
      this.snackBar.open("Simulator Updated Successfully!", "Success", {
        duration: 2000,
        verticalPosition: "top"
      });
    });
  }


  }

}

我的employeeReportsComponent.ts

import { Component, OnInit, ViewChild, ChangeDetectorRef } from '@angular/core';
import { MatPaginator, MatSort, MatTableDataSource } from '@angular/material';
import { SelectionModel } from '@angular/cdk/collections';
import { WebSocketService } from './../../core/services/web-socket.service';
import { Reports } from './Reports';

@Component({
  selector: 'app-reports',
  templateUrl: './employeeReports.component.html',
  styleUrls: ['./employeeReports.component.scss']
})
export class employeeReportsComponent implements OnInit {
  Reports;

  constructor(private socketService: WebSocketService) {

  }

  ngOnInit() {

    this.GetReports();
  }

  GetReports() {
    this.socketService.GetEmployeeReportData().subscribe((response) => {
      this.Reports = response;

      console.log(this.Reports);
    },
      (error) => (console.log(error))
    );
    this.changeDetect.detectChanges();
  }


}

我正在关注this文章

问题

当我在组件中多个用户订阅时,方法调用多次?

示例:当我使用三个订阅时,则方法调用三次。 我做错了吗?

我遵循的结构正确吗?我是新来的。

2 个答案:

答案 0 :(得分:0)

您将需要使用.pipe(share())在侦听器之间共享可观察对象。

https://blog.strongbrew.io/how-share()-can-reduce-network-requests/

https://www.learnrxjs.io/operators/multicasting/share.html

答案 1 :(得分:0)

根据rxjs doc的不同,它不会在每个请求上都创建一个新实例,只有在您将在每个WebSocketService方法上调用new wocketSubject('url')时,它才会为每次调用时,WebSocketSubject都会返回Subject,并在RXJS中将其称为 Hot Observable (热可观察),它表示它将从第一个订阅开始,然后从所有新订阅中获取该点的数据上。

在网络部分的chrome dev工具中的

PS,您可以查看它是否会创建一个新实例,如果您创建了一个新实例,它将创建一个新记录,如果您没有创建一个新实例,则会看到原始记录中的新邮件。