首页 > 解决方案 > 无法访问打字稿中的嵌套 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;
};

标签: jsonangulartypescriptnested-attributes

解决方案


你必须像这样解析它:

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;
                }
            });

推荐阅读