0

I am trying to use a GET request to receive data to put into a local variable. I have been able to get the local variable to display its data in the console admin if this is within the subscibe code. However, when i place the console.log outside, it does not work. Why is "this.taskSchedule" not displaying in the console?

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);
  }
}

In the console output, it just says "undefined". It should output the API data

GolfBravo
  • 837
  • 2
  • 12
  • 23

1 Answers1

0

Because you are trying to access it after the subscribe block which is asynchronous. Read through my comments.

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);
}
Immad Hamid
  • 789
  • 1
  • 8
  • 21