等待方法执行,然后在Angular中执行下一个代码

发布于 2025-02-09 19:58:47 字数 492 浏览 1 评论 0原文

我正在尝试在订阅方法之外使用requestDetails变量,但它显示“未定义”

服务

  requestDetails$ = new Subject<any>();
  updateApprovalMessage(message: string) {
  this.requestDetails$.next(message)
  }

。TScomponent.ts

requestDetails:any

this.technicalRequestService.requestDetails$.subscribe(data=>{
this.requestDetails=data
console.log(this.requestDetails)
//here it is printing
}
console.log(this.requestDetails)
//but its is showing undefined

I am trying to use the requestDetails variable outside the subscribe method but its showing "undefined"

service.ts

  requestDetails$ = new Subject<any>();
  updateApprovalMessage(message: string) {
  this.requestDetails$.next(message)
  }

component.ts

requestDetails:any

this.technicalRequestService.requestDetails$.subscribe(data=>{
this.requestDetails=data
console.log(this.requestDetails)
//here it is printing
}
console.log(this.requestDetails)
//but its is showing undefined

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

等数载,海棠开 2025-02-16 19:58:47

请注意,首先记录的不确定是如何的?

那是因为您的回调函数尚未被调用。如果要在this.requestdetails = Data之后执行代码,则必须在功能中进行。您当然也可以从这里调用其他方法。

ngOnInit() {
  this.technicalRequestService.requestDetails$.subscribe(data=>{
    this.requestDetails=data;
    console.log(this.requestDetails);
    afterSettingRequestDetails();
  }
}

afterSettingRequestDetails(){
  console.log(this.requestDetails);
}

或者,如果您喜欢async/等待

async ngOnInit() {
  this.requestDetails = await firstValueFrom(this.technicalRequestService.requestDetails$);
  console.log(this.requestDetails);
}

但这只会触发一次,对单个请求有用,但无用。

Notice how undefined is logged first?

That's because your callback function hasn't been called yet. If you want to execute code after this.requestDetails=data, you will have to do so inside the function. You can of course call other methods from here as well.

ngOnInit() {
  this.technicalRequestService.requestDetails$.subscribe(data=>{
    this.requestDetails=data;
    console.log(this.requestDetails);
    afterSettingRequestDetails();
  }
}

afterSettingRequestDetails(){
  console.log(this.requestDetails);
}

Or if you prefer async / await

async ngOnInit() {
  this.requestDetails = await firstValueFrom(this.technicalRequestService.requestDetails$);
  console.log(this.requestDetails);
}

But this will only fire once, useful for single requests but not data streams.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文