【问题标题】:Accessing obejct in object in json format in Typescript在Typescript中以json格式访问对象中的对象
【发布时间】:2018-12-26 10:57:35
【问题描述】:

我正在使用来自 Angularjs 6 的 rest API。我从控制台中的 API 得到这样的响应。

{
"flag": true,
"msg": "User credentials are matched",
"data": {
    "userId": 1234566,
    "password": "67899877@abdc",
    "firstName": "abcd",
    "lastName": "fghj",
    "email": "abcd@gmail.com",
    "status": 0,
    "role": 4
}
}

下面提到了我的角码:

import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';

 @Component({
 selector: 'app-root',
 templateUrl: './app.component.html',
 styleUrls: ['./app.component.css']
 })
 export class AppComponent implements OnInit {
  title = 'getting-started-angular';

  constructor(private http: HttpClient) {}

  ngOnInit(): void {
   interface UserResponse {
      userId: Int16Array;
      password: String;
      firstname: String;
      lastname: String;
      status: Int16Array;
      role: Int16Array;
 }


  interface  UserValues {
flag: boolean;
msg: string;
 data: Object;
  }


 this.http.get<UserValues>('http://localhost:8080/v1/user? 
 userId=1234566&password=67899877@abdc').subscribe(result => {

  console.log(result);
console.log('flag:' + result.flag);
console.log('msg:' + result.msg);
console.log('firstname:' + result.data);
  });

  }
  }

现在我可以在登录时从控制台访问标志和消息。 如何访问数据:{} JSON 响应中的值??

【问题讨论】:

  • 你试过result.data.firstName吗?
  • 是的。但它没有给我结果。
  • “UserValues”类型上不存在属性“数据”。收到此错误

标签: angularjs json rest angular-httpclient


【解决方案1】:

接口应该是这样的。

interface UserResponse {
      userId: Int16Array,
      password: string,
      firstName: string,
      lastName: string,
      email: string
      status: Int16Array,
      role: Int16Array,
 }

 interface  UserValues {
      flag: boolean;
      msg: string;
      data: UserResponse;
 }


console.log('firstname:' + result.data.firstName);

【讨论】:

  • 谢谢!!@fawad-mukhtar 它正在工作。所以json中的响应和angular中的接口声明应该是相同的格式??
  • 当您使用 this.http.get 语句时。此处的 UserValues 表示您希望得到这种格式的响应。应该是一样的
  • 我明白了。谢谢!! @fawad-mukhtar
  • 添加了一个问题。如何在 html 文件中显示此 JSON 数据。我使用 {{ result}} 格式。但它没有显示数据。
  • 结果是一个局部变量。在类中声明一个公共属性,就像您声明的标题变量一样。然后将此局部变量结果分配给那个并在 html 模板中使用。
猜你喜欢
  • 1970-01-01
  • 2020-12-25
  • 1970-01-01
  • 2016-07-02
  • 2019-11-03
  • 2016-07-28
  • 1970-01-01
  • 1970-01-01
  • 2018-02-10
相关资源
最近更新 更多