Использование Websocket Подписаться звонить несколько раз? - PullRequest
0 голосов
/ 20 октября 2018

My 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$;
     }
    }

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


  }

}

my 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 article

Вопрос

Когда я использую несколько подписок на компоненты, то вызов метода происходит несколько раз?

пример: когда я используютри подписались, затем вызов метода три раза.Я делаю неправильно?

Правильно ли я придерживался структуры или нет?я новичок в угловой.

1 Ответ

0 голосов
/ 20 октября 2018

Вам нужно будет использовать .pipe (share ()), чтобы поделиться наблюдаемым между слушателями.

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

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

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...