订阅Observer,然后将响应输出到控制台,返回未定义

问题描述 投票:-1回答:3

[当我订阅由Angular Component中的服务提供的API端点时,我无法从打字稿代码中的可观察值访问值,但是可以在HTML中看到它们。

role.service.ts

getAllRoles() {
    return this.http.get<Role[]>(`${environment.privateApiUrl}/Role/Get`);
}

app-component.component.ts

  roles: Role[];

  ngOnInit(): void {

    this.roleService.getAllRoles().subscribe(data => {
      this.roles = data
    })

    console.log(this.roles) <-- Returns undefined
  }

但是,如果我在HTML中调用角色,则可以看到所有值。如果在订阅中调用console.log,则可以看到这些值。

订阅后如何在Typescript中访问此对象?

谢谢

angular typescript angular2-observables
3个回答
1
投票

这是因为Subscriptions是异步代码。因此,在您的处理程序复制数据之前,将执行console.log。如果将console.log放在订阅中,它将起作用。

如果您以后想要访问,可以执行类似的操作

observable.subscribe(data => {
  this.data = data
  this.dataFunction()
})

并且让组件内部的dataFunction()在之后访问this.data,因为它将在那时定义。


0
投票

在用户函数内调用console.log

roles: Role[];

ngOnInit(): void {

  this.roleService.getAllRoles().subscribe(data => {
    this.roles = data
    console.log(this.roles);
  });
}

0
投票

订阅是Observable和Observer之间的合同。正如文档所述:“订阅Observable就像调用一个函数,该函数传递向其传递数据的回调。[...]执行随着时间的推移会同步或异步生成多个值。存在三种类型的值可观察的执行可以交付:

  • “下一个”通知:发送一个值,例如数字,字符串,对象等。
  • “错误”通知:发送JavaScript错误或异常。
  • “完成”通知:不发送值。“

订阅看起来可能像这样:

// get something
this.http.get<any[]>(`${AppConfig.settings.whatever}`).subscribe({
        next: (res: Array<any>) => {
          this.bucket = res;
          console.log('Response object: ', res);
        },
        error: (err: HttpErrorResponse) => { console.error('An error in getSomething occured', err.type) },
        complete: () => { 
          console.log('getSomething completed!');
          this.someService.setResponseObject(this.bucket);
          window.scrollTo(0, 0);
        }
      })

在这里看看:

并且也许观看此视频:

© www.soinside.com 2019 - 2024. All rights reserved.