Дублирование Http-запросов с использованием сервиса Angular 6 - PullRequest
0 голосов
/ 30 октября 2018

Я пытаюсь удалить объект из моей базы данных в .Net Core 2.1 + Angular Application. Однако каждый раз, когда я звоню, создаются две записи.

Во время отладки выясняется, что вызов сделан и происходит дважды. На вкладке «Сеть» консоли отображаются два повторяющихся вызова, и при прослушивании на сервере каждая точка останова повторяется дважды. Эти вызовы происходят в унисон, а не последовательно, так как мне приходится дважды щелкать по каждой точке останова, прежде чем перейти к следующей.

Я рассмотрел использование оператора share, но он либо не помогает, либо я не реализую его правильно?

Любая помощь приветствуется,

Module.ts

import { BusinessUnitService } from './../../services/business- 
unit.service';
import { Component, OnInit } from '@angular/core';
import { MatDialogRef } from '@angular/material';
import { ToastrService } from 'ngx-toastr';
import 'rxjs/add/operator/share';

@Component({
selector: 'app-businessunit-create',
templateUrl: './businessunit-create.component.html',
styleUrls: ['./businessunit-create.component.css']
})

export class BusinessunitCreateComponent implements OnInit {

companies = [];
businessUnit: any = {};

constructor(private dialogRef: MatDialogRef<BusinessunitCreateComponent>,
private businessUnitService: BusinessUnitService,
private toastr: ToastrService) { }

ngOnInit() {
this.businessUnitService.getCompanies().subscribe(res => {
  this.companies = res;
  console.log(res);
});
}

createBusinessUnit() {
console.log(this.businessUnit);
this.businessUnitService.addBusinessUnit(this.businessUnit).share().subscribe(res => {
  this.toastr.success('New Line of Business added successfully');
  this.dialogRef.close('ok');
},
  err => {
        this.toastr.error('Line of Business could not be added: ' + err);
});
}
}

Service.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { map } from 'rxjs/internal/operators/map';
import { share } from 'rxjs/operators';

@Injectable({
   providedIn: 'root'
})
export class BusinessUnitService {

addBusinessUnit(bu) {
   return this.http.post('/BusinessUnit/NewBusinessUnit', bu).pipe(share());
} 

HTML Где называется

 <mat-dialog-actions>
<button class="mat-raised-button" (click)="close()">Close</button>
<button class="mat-raised-button mat-primary" (click)="createBusinessUnit()" 
    [disabled]="!f.valid">Save Line of Business</button>
</mat-dialog-actions>

* Отредактировано для наглядности

1 Ответ

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

Итак, хотя мой component.ts вызывал функцию только дважды, оказалось, что я поместил имя функции в заголовок. Так как я сделал

<form (ngSubmit)="createBusinessUnit()" #f="ngForm">

эта функция была вызвана, когда я нажал кнопку "отправить" в моей форме, которая снова вызывала функцию. В результате функция Angular, которая вызывала мой http-сервис, вызывалась дважды, когда я нажимал кнопку в нижней части экрана.

<div class="form-group">
    <label for="buName">Name: </label>
    <input id="buName" type="text" class="form-control" [(ngModel)]="businessUnit.Name" name="buName" required #buName="ngModel">
    <div class="alert alert-danger" *ngIf="(buName.touched || buName.dirty) && !buName.valid">
      Please provide a Name for Line of Business.
    </div>
  </div>
  <div class="form-group">
  <label for="buNameKey">Name Key:</label> <br/>
  <small> *Warning: NameKey must be unique among Lines of Business</small>
  <input id="buNameKey" type="text" class="form-control" [(ngModel)]="businessUnit.NameKey" name="buNameKey"
  #buNameKey="ngModel" required minlength="3" maxlength="3">
<div class="alert alert-danger" *ngIf="(buNameKey.touched) && !buNameKey.valid">
  <div *ngIf="buNameKey.errors.required">
    Please provide a 3 character Name Key.
  </div>
  <div *ngIf="buNameKey.errors.minlength">
    Name Key must be at least 3 characters long.
  </div>
</div>
</div>
<div class="form-group">
 <label for="buDesc"> Description: </label>
 <input id="buDesc" name="buDesc" type="text" class="form-control" 
[(ngModel)]="businessUnit.Description">
</div>
<div class="form-group">
<label for="company">Company</label>
<select id="company" class="form-control" [(ngModel)]="businessUnit.CompanyID" 
name="company" required #company="ngModel">
  <option *ngFor="let company of companies" value="{{company.item1}}"> 
  {{company.item2}}</option>
</select>
<div class="alert alert-danger" *ngIf="company.touched && !company.valid">
   Please select a Company.
</div>
</div>
<mat-dialog-actions>
<button class="mat-raised-button" (click)="close()">Close</button>
<button class="mat-raised-button mat-primary" (click)="createBusinessUnit()" 
[disabled]="!f.valid">Save Line of Business</button>
 </mat-dialog-actions>
</form>

Спасибо за помощь, ребята!

...