gpt4 book ai didi

angular - 如何在 Angular 2 轮询服务中访问 .subscribe 之外的值

转载 作者:行者123 更新时间:2023-12-04 04:20:54 25 4
gpt4 key购买 nike

//我试图从订阅外部获取值,但它不能分配给任何变量。在我的项目中,使用 http.post() 方法获取 json 内容并将其分配给一个变量。我想在构造函数之外访问这些变量值。我怎样才能让它成为可能?

ngOnInit(): void {
this.getSubscription();
}

// here is my subscription function

getSubscription() {
interval(5000)
.pipe(
startWith(0),
switchMap(() => this._subscriptionService.getSubData()))
.subscribe(data => {
this.Result = data; // able to print the data
JSON.stringify(this.Result);

console.log(this.Result); // able to print the data
});

console.log(this.Result); // undefined is printing
}

//我想在订阅外访问 this.result 并分配给一个公共(public)变量

最佳答案

您在 ngOnInit 中调用 getSubscription() 并且此时执行您的变量 Result 未设置,因为您的 http请求异步。在您的订阅方法第一次执行后,变量被设置。

如果其他函数需要该值,我建议您从您的订阅中调用它们,否则您无法确定您的 http 请求何时完成。

getSubscription() {
interval(5000)
.pipe(
startWith(0),
switchMap(() => this._subscriptionService.getSubData()))
.subscribe(data => {
this.Result = data; // able to print the data
JSON.stringify(this.Result);

console.log(this.Result); // able to print the data

// Is called every time you get a new result and this.Result is set now
this.processResults();
});

// Not set yet
console.log(this.Result); // undefined is printing
}

processResults() {
// Do some stuff with your results, this.Result is set now
}

关于angular - 如何在 Angular 2 轮询服务中访问 .subscribe 之外的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50984258/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com