在Typescript中以json格式访问对象中的obejct

时间:2018-12-26 10:57:35

标签: angularjs json rest angular-httpclient

我正在使用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响应中的数据:{}值?

1 个答案:

答案 0 :(得分: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);