Angular服务未将数据分配给局部变量[duplicate]

问题描述 投票:0回答:1

我正在尝试使用GET请求来接收要放入本地变量的数据。如果这在subscibe代码内,我已经能够获取本地变量以在控制台admin中显示其数据。但是,当我将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);
  }
}

在控制台输出中,它只是说“未定义”。它应该输出API数据

angular rest service
1个回答
0
投票

因为您正在尝试在异步的预订块之后访问它。通读我的评论。

ngOnInit() {
    // This is an asynchronous function
    this.taskScheduleService.getTaskSchedule(19).subscribe(data => {
      this.taskSchedule = data;
      // Here you can access this.taskSchedule
    });
    // 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);
}
© www.soinside.com 2019 - 2024. All rights reserved.