json - 无法访问打字稿中的嵌套 JSON 数据 - Angular6
问题描述
我收到的响应是 JSON 数组,格式如下:
{
"response": {
"refreshToken": "sometoken",
"token": "sometoken",
"user": {
"active": 12,
"id": 5,
"name": "abc",
"password": "def"
}
}
}
现在我想在打字稿中访问名称和密码。
this._scaffolder.AuthGuard.authenticate(JSON.stringify(requestBody))
.subscribe(response => {
this._logger.info(response);
if (response && response.valid) {
console.log(response.user.name);
this._scaffolder.Cluster.API.silentlyNavigate('model');
} else {
this.areCredsInvalid = true;
}
});
我在尝试访问名称字段的地方尝试过这个。
但我看到一个错误:类型响应中不存在属性用户。响应对象如下图,其中user是UserModel的一个对象
response: {
valid: boolean;
response: PlatformServiceProxy.ErrorResponse | {
token: string;
refreshToken: string;
user: PlatformServiceProxy.UserModel;
};
解决方案
你必须像这样解析它:
this._scaffolder.AuthGuard.authenticate(JSON.stringify(requestBody))
.subscribe(response => {
this._logger.info(response);
if (response && response.valid) {
let userDict = response['response']['user']
console.log(userDict.name); // for accessing name as its in the form of dictionary (key-value pair)
console.log(userDict.password); // for accessing password
this._scaffolder.Cluster.API.silentlyNavigate('model');
} else {
this.areCredsInvalid = true;
}
});
推荐阅读
- file - 在目录中查找重复文件
- excel - 使用 VBA 查找和替换连续单元格中的值
- c - 在 FINTEK F81866A 芯片组上编程 GPIO 引脚
- hadoop - Hadoop权威指南的面向列的格式章节中的序列顺序?
- ruby - 自定义 Ruby on rails 验证错误
- kubernetes - Unabel 使用 openstack-helm 图表在 kubernetes 上部署 mariadb
- javascript - Marvel API 和 Insomnia(或 Postman):如何传递所需的哈希值?
- node.js - 你如何使用 distinct 和 mockingoose?
- python - 检查我的观点是否在我的屏幕的一部分
- c++ - 如何使用 break 停止循环?