如何从Angular的可观察到的JSON文件中获取组件?

发布于 2025-02-13 17:51:23 字数 311 浏览 1 评论 0原文

考虑代码:

res: any;

getData(url: any) {
    this.res = this.http.get(url);
}

ngOnInit(): void {
     getData("url.com/file.json");
     console.log(this.res)
}

在控制台中,我得到了

Observable {source: Observable, operator: ƒ}

如何获得JSON文件的内容而不是可观察的?

Consider the code:

res: any;

getData(url: any) {
    this.res = this.http.get(url);
}

ngOnInit(): void {
     getData("url.com/file.json");
     console.log(this.res)
}

In the console I get

Observable {source: Observable, operator: ƒ}

How do I get the contents of the json file instead of an observable?

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

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

发布评论

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

评论(2

泅渡 2025-02-20 17:51:24

您需要订阅可观察的。

getData(url: any) {
    this.http.get(url).subscribe(result => { this.res = result; });
}

You need to subscribe to the observable.

getData(url: any) {
    this.http.get(url).subscribe(result => { this.res = result; });
}
演出会有结束 2025-02-20 17:51:23

首先,定义属性并使用httpclient动词的方式。如果要将http动词(IE get)分配给属性,则该属性将保持可观察的,因为httpclient动词返回ObservablesAngular中,它们由引擎盖下的rxjs提供动力。

其次,话虽如此,如果您想进入json部分,您需要订阅可观察的 ie ie,请收听由观察者。

您有两种方法来做到这一点。

1-根据Andrew的描述,通过将JSON调查到订阅中的属性中。

2-您将属性保留为可观察的,并在模板中使用async管道。

现在,为什么您会得到不确定的?因为在组件的初始化过程中,您的异步数据尚未被调解为您的属性。在这里,您有多个选项,包括使用不同的生命周期钩,例如ngafterviewinit或使用警卫条件检查

if(res) { //stuff}

所有情况,您需要对非常规的处理HTTP调用的小型重构,就像在您的情况下一样上面的代码片段。

First, the way you define the property and use the httpClient verbs in unconventional. If you want to assign the Http verb (i.e GET) to a property this property will hold an Observable, because HttpClient verbs return Observables in Angular and they are powered by RxJS under the hood.

Second, with this being said, if you want to get into the JSON part you need to subscribe to the Observable i.e listen to the values that will be broadcasted by the Observer.

You have two ways to do that;

1 - As per Andrew description by assinging the JSON to the property within the subscription.

2- You keep the property assigned an Observable and use async pipe in your template.

Now, why you are getting undefined ? because during initialization of the component your asynchronous data has not been assinged yet to your property. Here, you have multiple options, including using a different lifecycle hook such as ngAfterViewInit or use a guard condition to check

if(res) { //stuff}

In all cases, you need a small refactoring for the unconventional way of handling Http calls as in your code snippets above.

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