【问题标题】:Angular service not assigning data to local variable [duplicate]Angular服务未将数据分配给局部变量[重复]
【发布时间】:2020-04-09 22:30:03
【问题描述】:

我正在尝试使用 GET 请求来接收要放入局部变量的数据。如果这在 subscibe 代码中,我已经能够获取局部变量以在控制台管理员中显示其数据。但是,当我将 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】:

    因为您试图在异步订阅块之后访问它。通读我的 cmets。

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

    【讨论】:

    • 但是如何在订阅块之外访问它?
    • 您可以在外部访问它,但只能在订阅块执行时访问。让我给你看一个例子。一分钟后再次检查我的答案
    猜你喜欢
    • 1970-01-01
    • 2016-10-09
    • 1970-01-01
    • 1970-01-01
    • 2019-03-20
    • 1970-01-01
    • 1970-01-01
    • 2018-10-24
    • 2012-08-01
    相关资源
    最近更新 更多