Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/json/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在angular2中解析json_Json_Angular_Typescript - Fatal编程技术网

在angular2中解析json

在angular2中解析json,json,angular,typescript,Json,Angular,Typescript,我试图从服务中读取angular2应用程序中的用户数。 我们大摇大摆地从服务生成存根 我的存根(gpMapApi): 我的打字稿 public checkUserExist(oId,Id) { this.gpMapApi.findMapByIdsUsingGET(oId,id) .subscribe(response => { if ((<any>response) !== null &&

我试图从服务中读取angular2应用程序中的用户数。 我们大摇大摆地从服务生成存根

我的存根(gpMapApi):

我的打字稿

public checkUserExist(oId,Id) {
       this.gpMapApi.findMapByIdsUsingGET(oId,id)
             .subscribe(response => {
                  if ((<any>response) !== null && (<any>response)['_body'] !== null && (<any>response)['_body']['count'] !== null) {
                this.iCount = (<any>response)['_body']['count'];
        });      
    }
如何读取json响应

解决方案 使用
JSON.parse((response)。\u body.count

看起来您返回的是
未定义的
,但是您在Typescript中的检查是检查
null
[其中
!==
严格地说是不相等]

如果您将其更改为
=这可能会解决您的问题。如果没有,它肯定不会崩溃,并且正确地遵循您的If条件

编辑: 如果您遇到JSON解析问题,并且
response
变量是字符串,那么您可以通过
JSON.parse(response)
而不是
response.JSON()
来获取对象

编辑最终版本:
根据您的评论,很明显,
(响应)。\u body
是一个字符串,可以通过运行
typeof(响应)进行验证。\u body
。基于此,解决方案是简单的
JSON.parse((response)。\u body.count

这是我得到的错误,属性“JSON”在类型“string”上不存在。您可以记录响应:
console.log(response)
?response\u body:“{”count:0}”
console.log(response)
的结果是什么?在你的帖子中,你说“我的Json响应:
{“count”:0}
。然后直接使用
response['count']
修改代码后,它没有进入循环。对,这意味着
(response)[''u body']
未定义。我建议您使用
console.log(response)
来确定设置了哪些键,如果您可能使用了错误的键,这是我的响应体:“{”count“:0}”,我不确定如何检索值0。如果我尝试这个console.log('response',(response)['u body']['u count']);我得到了未定义的响应。但是console.log('response',(response)[“body]”);获取{“count”:0}谢谢,这有效了Soln:JSON.parse((response)。\u body.count
{"count" : 0}
public checkUserExist(oId,Id) {
       this.gpMapApi.findMapByIdsUsingGET(oId,id)
             .subscribe(response => {
                  if ((<any>response) !== null && (<any>response)['_body'] !== null && (<any>response)['_body']['count'] !== null) {
                this.iCount = (<any>response)['_body']['count'];
        });      
    }
"Cannot read property 'count' of undefined"