Angular не отображает данные из component.ts в html

#typescript #angular7

#typescript #angular7

Вопрос:

Я пытаюсь отобразить office в раскрывающемся списке select элемент. Я проверил / подтвердил, что мой api возвращает правильные данные. Однако в моем файле angular component (ts и html) я не смог его отобразить.

файл модели

 export interface Office {
  id: string;
  name: string;
  sections: Array<Sections>;
}

export interface Sections {
  id: string;
  name: string;
  code: string;
}
  

служебный файл

 getOffices() {
  return this.http.get<{offices: Office[]}>(`${BACKEND_URL}`);
}
  

файл компонента

 offices: Office[] = [];

constructor(public officesService: OfficesService) {}

  ngOnInit() {

    return this.officesService.getOffices().subscribe((officesData: {offices: Office[]}) => {
      this.offices = officesData.offices;
    });

  }

//at this point I can see from my browser Network tab the offices preview and the data are correct
  

html-файл

 <mat-select name="office" placeholder="Office" #officeInput="ngModel" matInput ngModel required>
  <mat-option *ngFor="let office of offices" value="">{{ office.name }}</mat-option>
</mat-select>
  

Ответ №1:

Если для вашего компонента установлено значение обнаружение изменений OnPush , вам необходимо вручную запускать обнаружение изменений при изменении данных без изменения входных данных:

 offices: Office[] = [];

constructor(public officesService: OfficesService, private cd: ChangeDetectorRef) {}

ngOnInit() {

  return this.officesService.getOffices().subscribe((officesData: {offices: Office[]}) => {
    this.offices = officesData.offices;
    this.cd.markForCheck();
  });

}
  

Ответ №2:

я думаю, вы пытаетесь получить доступ к данным, которых не существует.

в сервисе, который вы ожидаете получить, office -> return this.http.get<{offices: Office[]}>( $ {BACKEND_URL} );

Но в компоненте, который вы пытаетесь получить (officesData: {offices: Office[]})

Попробуйте это —

this.officesService.getOffices().subscribe((offices: Office[]) => this.offices = offices);