【问题标题】:Not able to access nested JSON data in typescript - Angular6无法访问打字稿中的嵌套 JSON 数据 - Angular6
【发布时间】:2019-08-26 05:43:59
【问题描述】:

我收到的响应是 JSON 数组,格式如下:

{
  "response": {
    "refreshToken": "sometoken",
    "token": "sometoken",
    "user": {
      "active": 12,
      "id": 5,
      "name": "abc",
      "password": "def"
    }
  }
}

现在我想在 typescript 中访问名称和密码。

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._logger.info(response); 显示什么?
  • authenticate 函数长什么样子?

标签: json angular typescript nested-attributes


【解决方案1】:

由于在响应中,user 位于另一个 response 对象中,因此您也必须添加它。

试试:

console.log(response.response.user.name);

【讨论】:

    【解决方案2】:

    你必须这样解析它:

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

    【讨论】:

      【解决方案3】:

      希望你做得很好!!!

      以下是您可以使用的解决方案,其中添加了 2 个场景以供您帮助。我在 Pure RXJs 中执行此操作,以便任何其他遇到此问题的 JS 框架用户都可以受益。

      场景 1:如果整个对象作为响应与其他请求/响应标头一起出现,则使用:-

      import { ajax } from 'rxjs/ajax';
      import { map } from 'rxjs/operators';
      
      ajax('https://my-json-server.typicode.com/nimpossible/json-server/db')
        .pipe(
        map(ajaxResponse => {
          const { response: { response: res } } = ajaxResponse; // ES6 Destructuring Used
          return res.user; // here 'res' is an alias used above
          })
       )
        .subscribe(mappedValue => {
          console.log(mappedValue.name);
          console.log(mappedValue.password);
        });
      

      场景 2:如果只有响应对象直接作为响应而没有其他请求标头,则使用:-

      import { ajax } from 'rxjs/ajax';
      import { map } from 'rxjs/operators';
      
      ajax.getJSON('https://my-json-server.typicode.com/nimpossible/json-server/db')
        .pipe(
        map(ajaxResponse => {
            const { response: res } = ajaxResponse; // ES6 Destructuring Used
            return res.user; // here 'res' is an alias used above
          })
        )
        .subscribe(mappedValue => {
          console.log(mappedValue.name);
          console.log(mappedValue.password);
        });
      

      在您的情况下,考虑到您随问题提供的响应对象,场景 2 可能会起作用。

      希望这会有所帮助!快乐编码!干杯!!!

      【讨论】:

        猜你喜欢
        • 2021-03-02
        • 1970-01-01
        • 1970-01-01
        • 2021-11-23
        • 2018-06-25
        • 1970-01-01
        • 2019-08-03
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多