首页 > 解决方案 > 每当在Angular中更改要发布的元素时如何刷新对api的发布请求

问题描述

我正在尝试编写汽车租赁网站前端。api 有一个 api/filter 控制器,我需要发布过滤器对象:

export interface Filter {
    brandNames:string[],
    colorNames:string[],
    priceMin:number,
    priceMax:number,
    dateStart:Date,
    dateEnd:Date
}

我将这个“过滤器”对象保存在 searchService 中:

@Injectable({
  providedIn: 'root'
})
export class SearchService {
  searchText: string = ""

  emptyDate:Date = new Date(0,0,0)

  readonly emptyFilter: Filter = {
    brandNames: [],
    colorNames: [],
    priceMin: 0,
    priceMax: 0,
    dateEnd: this.emptyDate,
    dateStart: this.emptyDate
  }
  filter: Filter = this.emptyFilter
}

我有几个侧边栏部分来操作过滤器的每个属性,侧边栏组件下有两个子组件,一个用于品牌名称,一个用于颜色名称。例如其中之一是:

<app-brand></app-brand>
<app-color></app-color>  
  
<div class="shadow pt-2">
      <form class="form-control">
        <label for="startDate" class="form-label">Start Date: </label>
        <input type="date" [value]="startDatePlaceHolder" min="{{minDate}}" class="form-date" id="startDate" 
            name="startDate" [(ngModel)]="selectedStartDate">
      <hr>
      <label for="dueDate" class="form-label">Due Date: </label>
      <input type="date" [value]="dueDatePlaceHolder" class="form-date" id="dueDate" name="dueDate" [(ngModel)]="selectedDueDate">
      
        <button type="button" (click)="setDateFilter()" class="btn btn-dark">Filter</button>
      </form>
    </div>
    
    <div class="shadow pt-2 d-grid gap-2">
      <button type="button" (click)="clearAllFilters()" class="btn btn-dark">Clear All Filters</button>
    </div>

现在的问题是,我想将此过滤器发布到 api 并动态更新汽车列表,以响应应通过单击品牌名称(=将单击的品牌名称添加到过滤器的品牌名称数组)或单击“过滤器”来调用的任何更改" 选择价格范围后的按钮。

这是 carDto 服务:

constructor(private httpClient: HttpClient) { }
  getCarDtoListByFilter(filter: Filter): Observable<any> {

    let path = this.apiUrl + "/filter"
    return this.httpClient.post(path, filter, this.options)
  }

这是列出 carDtos 的组件:

  constructor(private carDtoService: CarDtoService,
    private carImageService: CarImageService,
    private searchService: SearchService) { }

  ngOnInit(): void {
    this.getCarDetailsListByFilter()
  }

  getCarDetailsListByFilter() {
    this.carDtoService.getCarDtoListByFilter(this.searchService.filter).subscribe(result => {
      this.carDtoList = result.data
    })
  }

侧边栏和carDtoList的文件夹结构外观

标签: javascriptangulartypescriptfrontendangular11

解决方案


你必须放弃 ngModel 并使用响应式表单。

组件控制器:

selectedStartDate: FormControl = new FormControl('');

ngOnInit(): void {
  this.selectedStartDate.valueChanges
      .pipe(
         startsWith(''),
         distinctUntilChanged()
      ).subscribe(value => {
           // send filter value
           this.getCarDetailsListByFilter();
      });
}

模板

 <input type="date" [value]="startDatePlaceHolder" min="{{minDate}}" class="form-date" id="startDate" 
            name="startDate" [formControl]="selectedStartDate">

推荐阅读