简体   繁体   中英

Accessing obejct in object in json format in Typescript

I am consuming rest API from Angularjs 6. I have response like this from API in the console.

{
"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
}
}

My angular code is mentioned below:

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

  }
  }

Now i am able to access flag and message from console when i logged. How can i access data:{} values from JSON response??

Interfaces should be like this.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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