简体   繁体   English

如何在Angular 4中从API接收响应

[英]How to receive response from API in Angular 4

I am working in an Angular 4 application,Trying to get data from API,In this I don't know whether I am receiving the response or not ,But I don't receive any error. 我在Angular 4应用程序中工作,试图从API获取数据,在此我不知道我是否正在接收响应,但是我没有收到任何错误。

This is what I have tried... 这就是我尝试过的...

ngOnInit() {
    this.http.get(`url=${this.product_Name}`)
     .subscribe(data => { this.path = data[0].Image_PATH_NAME;}, error => console.error(error));
     } 
 } 

This is the JSON response I got from API 这是我从API获得的JSON响应

[{"Image_PATH_NAME":"assets/Images/Product_Details_Page/Show101.png"}]

While debugging the above lines I can't see any kind of response .I am new to Angular4 please guide me to get API response. 在调试上述代码时,我看不到任何响应。我是Angular4的新手,请引导我获取API响应。

This is the answer for this question. 这就是这个问题的答案。

.subscribe(data => {
      console.log(data[0]['Image_PATH_NAME']);
    });

console view. 控制台视图。

在此处输入图片说明

It looks like you are using the old HttpModule in which case, you have to convert your response to JSON before use : 看起来您正在使用旧的HttpModule在这种情况下,必须在使用前将响应转换为JSON:

ngOnInit() {
    this.http.get(`url=${this.product_Name}`)
     .map(res => res.json())
     .subscribe(data => { this.path = data[0].Image_PATH_NAME;}, error => console.error(error));
     } 
 } 

if you pass in 如果你通过

this.path = data[0].Image_PATH_NAME;

it means your http call finished correctly. 这表示您的http通话已正确完成。 When you use subscribe, the first parameter is a function called when the call finished correctly, the second parameter is a function called when something went wrong. 当您使用订阅时,第一个参数是调用正确完成时调用的函数,第二个参数是发生错误时调用的函数。

You can also check the network section in you devtools and look for you http call to see what you got 您还可以在devtools中检查“网络”部分,并查找http呼叫以查看获得的内容

Hope that helps 希望能有所帮助

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM