如何从Angular的可观察到的JSON文件中获取组件?
考虑代码:
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 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您需要订阅可观察的。
You need to subscribe to the observable.
首先,定义属性并使用
httpclient
动词的方式。如果要将http动词(IEget
)分配给属性,则该属性将保持可观察的
,因为httpclient
动词返回Observables
在Angular
中,它们由引擎盖下的rxjs
提供动力。其次,话虽如此,如果您想进入
json
部分,您需要订阅可观察的
ie ie,请收听由观察者。
您有两种方法来做到这一点。
1-根据Andrew的描述,通过将
JSON
调查到订阅中的属性中。2-您将属性保留为
可观察的
,并在模板中使用async
管道。现在,为什么您会得到
不确定的
?因为在组件的初始化过程中,您的异步数据尚未被调解为您的属性。在这里,您有多个选项,包括使用不同的生命周期钩,例如ngafterviewinit
或使用警卫条件检查所有情况,您需要对非常规的处理HTTP调用的小型重构,就像在您的情况下一样上面的代码片段。
First, the way you define the property and use the
httpClient
verbs in unconventional. If you want to assign the Http verb (i.eGET
) to a property this property will hold anObservable
, becauseHttpClient
verbs returnObservables
inAngular
and they are powered byRxJS
under the hood.Second, with this being said, if you want to get into the
JSON
part you need to subscribe to theObservable
i.e listen to the values that will be broadcasted by theObserver
.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 useasync
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 asngAfterViewInit
or use a guard condition to checkIn all cases, you need a small refactoring for the unconventional way of handling Http calls as in your code snippets above.