Я пытаюсь использовать запрос GET для получения данных для помещения в локальную переменную. Мне удалось заставить локальную переменную отображать свои данные в консоли администратора, если это находится в коде подписки. Однако, когда я размещаю console.log снаружи, он не работает. Почему «this.taskSchedule» не отображается в консоли?
export class TestTaskComponent implements OnInit {
profileForm: FormGroup;
taskSchedule: any = {};
constructor(
private taskScheduleService: TaskScheduleService,
private stateStorageService: StateStorageService,
private router: Router) { }
ngOnInit() {
this.taskId = this.stateStorageService.getCurrentTaskId();
this.taskScheduleService.getTaskSchedule(19).subscribe(data => {
this.taskSchedule = data;
});
console.log(this.taskSchedule);
}
}
В выводе на консоль написано просто "undefined". Он должен выводить данные API
1 ответ
Потому что вы пытаетесь получить к нему доступ после блока подписки, который является асинхронным. Прочитайте мои комментарии.
ngOnInit() {
// This is an asynchronous function
this.taskScheduleService.getTaskSchedule(19).subscribe((data) => {
// Here you can access this.taskSchedule
this.taskSchedule = data;
// Here we know that the value is assigned and we will call another method
this.accessTaskSchedule();
});
// This is where the subscribe block ends so when you try to console this.taskSchedule you will find it empty or not yet assigned
console.log(this.taskSchedule);
}
// let's have another method where we could access the local variable
accessTaskSchedule() {
// here you would be able to access this because you made sure that you are using it after it's set
console.log(this.taskSchedule);
}
Похожие вопросы
Связанные вопросы
Новые вопросы
angular
Вопросы об Angular (не путать с AngularJS), веб-фреймворке от Google. Используйте этот тег для вопросов Angular, которые не относятся к отдельной версии. Для более старой веб-инфраструктуры AngularJS (1.x) используйте тег AngularJS.