Почему переменные моего объекта не определены после подписки - PullRequest
0 голосов
/ 23 марта 2020

Я новичок в Angular. Я использую Angular9. Я попытался подписаться на наблюдаемую, как вы прочтете в следующем:

У меня есть служба, которая вызывает HTTP-запрос и возвращает Observable. Подписка работает отлично. По крайней мере, это выглядит так.

ngOnInit() {
  this.initialDataViewModelSubscription = this.initialDataViewModelService.load()
     .subscribe(initialDataViewModel => {
        this.initialDataViewModel = initialDataViewModel;
     }, err => console.log(err));
}

На Html я использую форму Angular -Material для отображения содержимого.

<div>
  <mat-form-field>
  <mat-label>Mitarbeiter</mat-label>
    <input matInput placeholder="Mitarbeiter"
       [value]="this.getData()" <!-- To test the Data, value would be this.initialDataViewModel.curentEmployee-->
       [readonly]="true">
  </mat-form-field>
</div>

getData () в компоненте:

getData() {
    if (this.initialDataViewModel) {
      console.log('IDV:', this.initialDataViewModel)
      console.log('OK:', this.initialDataViewModel.OK)
      console.log('ASE:', this.initialDataViewModel.allowSelectEmployee)
      console.log('CD:', this.initialDataViewModel.currentDate)
      console.log('CE:', this.initialDataViewModel.currentEmployee)
    }
}

Приведенный выше код дает следующий результат:

IDV: {
      CurrentEmployee: {…}, 
      CurrentDate: "/Date(1584918000000)/", 
      AllowSelectEmployee: true, 
      SpecialProjectList: Array(7), 
      OK: true, …
     }
     > CurrentEmployee: {
          MitarbeiterId: 742, 
          MitarbeiterKuerzel: "GGG (NAME)", 
          MitarbeiterText: "GGG (NAME)", 
          MitarbeiterName: "Name"
       }
       CurrentDate: "/Date(1584918000000)/"AllowSelectEmployee: true
       SpecialProjectList: (7) [{…}, {…}, {…}, {…}, {…}, {…}, {…}]
       OK: true 
       Message: null
       __proto__: Object
}
component.component.ts:70 OK: true
component.component.ts:71 ASE: undefined
component.component.ts:72 CD: undefined
component.component.ts:73 CE: undefined

Насколько я вижу, мой Объект initialDataViewModel инициализирован и все переменные установлены. Но как только я хочу использовать переменную (например, currentEmployee), она не определена. Почему это так, что я делаю неправильно?

Редактировать:

@Component({
  selector: 'app-zeiterfassung',
  templateUrl: './zeiterfassung.component.html',
  styleUrls: ['./zeiterfassung.component.css']
})
export class ZeiterfassungComponent implements OnInit, OnDestroy{

  initialDataViewModel: InitialDataViewModel;

  initialDataViewModelObs: Observable<InitialDataViewModel>;

  initialDataViewModelSubscription;

  currentEmployee: EmployeeModel = new EmployeeModel();

  dateFormControl = new FormControl();

  projektFormControl = new FormControl('', Validators.required);

  dateClass;

  constructor(private initialDataViewModelService: InitialDataViewModelService) {
  }

  ngOnInit() {
    this.initialDataViewModelSubscription = 
    this.initialDataViewModelService.load().subscribe(initialDataViewModel => {
       this.initialDataViewModel = initialDataViewModel;
    }, err => console.log(err));
  }

  ngOnDestroy() {
    Utils.unsubscribeSubscription(this.initialDataViewModelSubscription);
  }

  getData() {
    if (this.initialDataViewModel) {
      console.log('IDV:', this.initialDataViewModel)
      console.log('OK:', this.initialDataViewModel.OK)
      console.log('ASE:', this.initialDataViewModel.allowSelectEmployee)
      console.log('CD:', this.initialDataViewModel.currentDate)
      console.log('CE:', this.initialDataViewModel.currentEmployee)
    }
  }

}

1 Ответ

1 голос
/ 23 марта 2020

Немного трудно понять, что именно происходит, без полного кода компонента, но я думаю, , что происходит, это то, что шаблон пытается использовать ваши данные до разрешения наблюдаемого. Как правило, я думаю, что вам нужно выполнить проверку существования ваших данных, если они заполняются наблюдаемой. Итак:

<div>
  <mat-form-field>
  <mat-label>Mitarbeiter</mat-label>
    <input *ngIf="initialDataViewModel" matInput placeholder="Mitarbeiter"
       [value]="initialDataViewModel"
       [readonly]="true">
  </mat-form-field>
</div>

тогда, ввод не будет отображаться до тех пор, пока данные не будут заполнены.

Кроме того, похоже, что переменная заглавная буква не соответствует.

allowSelectEmployee vs AllowSelectEmployee
currentDate vs CurrentDate
specialProjectList vs SpecialProjectList

др c

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