Angular (HTTP): два выбранных поля должны обновлять друг друга, но только одно делает - PullRequest
0 голосов
/ 08 сентября 2018

У меня есть два выбранных поля ввода в моем представлении HTML. Когда я нажимаю на первый, происходит запрос JSON, и мне отвечают некоторые идентификаторы, которые я хочу использовать позже, но уже для следующего ввода. Второе поле ввода берет выбранный идентификатор из первого ввода и запускает другой запрос API. Наконец, оно будет отображаться в let appointmentDate of appointmentDates Пока все хорошо.

Но одна вещь не удовлетворяет. Когда пользователь выбирает selectedAppointmentTypeId, но переключает поле выбора selectedAppointmentLocation, мой ответ appointmentDates не обновляется .

Как я могу заставить их работать вместе?

Это мой вид HTML:

<select 
  type="appointmentLocation" 
  [(ngModel)]="selectedAppointmentLocation" 
  (ngModelChange)="onChangeLocation($event)">
  <option 
    *ngFor="let appointmentLocation of appointmentLocations" 
    [ngValue]="appointmentLocation.id">
    {{appointmentLocation.name}}
  </option>
</select>
{{selectedAppointmentLocation}}

<select 
  type="appointmentType" 
  [(ngModel)]="selectedAppointmentTypeId" 
  (ngModelChange)="onChangeTypeId($event)">
  <option 
    *ngFor="let appointmentType of appointmentTypes | filter:false" 
    [ngValue]="appointmentType.id">
    {{appointmentType.name}}
  </option>
</select>
{{selectedAppointmentTypeId}}

<span 
  *ngFor="let appointmentDate of appointmentDates">
  {{appointmentDate.date}}
</span>

Это мой component.ts:

private appointmentLocations: Array < object > = [];
private appointmentTypes: Array < object > = [];
private appointmentDates: Array < object > = [];
selectedAppointmentTypeId: string;
selectedAppointmentLocation: string;

ngOnInit() {
  this.getData();
}

onChangeLocation(LocationId) {
  console.log(LocationId);
  this.selectedAppointmentLocation = LocationId;
}

onChangeTypeId(TypeId) {
  console.log(TypeId);
  this.selectedAppointmentTypeId = TypeId;
  this.apiService
    .getAppointmentDatesById(
      this.selectedAppointmentTypeId,
      this.selectedAppointmentLocation
    )
    .subscribe((data: Array < object > ) => {
      this.appointmentDates = data;
      console.log(data);
    });
}

public getData() {
  this.apiService
    .getAppointmentLocations()
    .subscribe((data: Array < object > ) => {
      this.appointmentLocations = data;
      console.log(data);
    });
  this.apiService.getAppointmentTypes().subscribe((data: Array < object > ) => {
    this.appointmentTypes = data;
    console.log(data);
  });
}

Это мой API.service:

getAppointmentDatesById(
  selectedAppointmentTypeId,
  selectedAppointmentLocation
) {
  return this.httpClient.get(
    `${this.API_URL}/availability/dates/${selectedAppointmentTypeId}/2018-09/${selectedAppointmentLocation}`
  );
}

1 Ответ

0 голосов
/ 08 сентября 2018

попробуйте принудительно повторно запустить второй выбор, если что-то уже было выбрано:

onChangeLocation(LocationId) {
  console.log(LocationId);
  this.selectedAppointmentLocation = LocationId;
  // check if a value exists and use it
  if(this.selectedAppointmentTypeId) {
    this.onChangeTypeId(this.selectedAppointmentTypeId);
  }
}

, поскольку вы фактически не изменяете второе значение выбора, оно не будет повторно запускать вашу функцию изменения без вашего специального запроса.

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