简体   繁体   English

无法访问打字稿中的嵌套JSON数据-Angular6

[英]Not able to access nested JSON data in typescript - Angular6

I am getting the response as a JSON array in the following form : 我以以下形式将响应作为JSON数组获取:

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

Now I want to access name and password in 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;
                }
            });

I have tried this where I try to access the name field. 我曾尝试在此尝试访问名称字段。

But I am shown an error that : Property user does not exist on the type response. 但是我看到一个错误:类型响应上不存在属性用户。 The response object is as shown below, where the user is an object of UserModel 响应对象如下所示,其中用户是UserModel的对象

response: {
    valid: boolean;
    response: PlatformServiceProxy.ErrorResponse | {
        token: string;
        refreshToken: string;
        user: PlatformServiceProxy.UserModel;
};

You have to parse it like that : 您必须像这样解析它:

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

Since in the response, user resides inside anothet response object, you have to add it too. 由于在响应中, user驻留在其他response对象中,因此您也必须添加它。

Try: 尝试:

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

Hope you're doing great!!! 希望你做的很棒!!!

Below is the solution you can use with 2 scenarios added for your help. 以下是可以与2种方案一起使用的解决方案,可以为您提供帮助。 I am doing this in Pure RXJs so that any other JS Framework user with this issue can be benefited. 我在Pure RXJs中这样做,以便使任何其他有此问题的JS Framework用户都能受益。

Scenario 1: If the entire object is coming as a response with other request/response headers, then use: - 方案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);
  });

Scenario 2: If only the response object is coming directly as a response with no other request headers then use: - 方案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);
  });

In your case, maybe Scenario 2 will work, considering the response object you have provided with the question. 在您的情况下,考虑到您随问题提供的响应对象,方案2可能会起作用。

Hope this helps! 希望这可以帮助! Happy Coding! 编码愉快! Cheers!!! 干杯!!!

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

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