I'm getting JSON data in spring boot and tryin

2019-09-19 09:49发布

问题:

This the model that I've.

@Entity
@Table(name = "tbl_user")
public class User {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    @Column(name = "id")
    long id;

    @Column(name = "first_name")
    String firstName;

    @Column(name = "last_name")
    String lastName;

    @Column(name = "email")
    String email;

    @Column(name = "contact")
    String contact;

    @Column(name = "status")
    String status;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getFirstName() {
        return firstName;
    }

    public void setFirstName(String firstName) {
        this.firstName = firstName;
    }

    public String getLastName() {
        return lastName;
    }

    public void setLastName(String lastName) {
        this.lastName = lastName;
    }

    public String getEmail() {
        return email;
    }

    public void setEmail(String email) {
        this.email = email;
    }

    public String getContact() {
        return contact;
    }

    public void setContact(String contact) {
        this.contact = contact;
    }

    public String getStatus() {
        return status;
    }

    public void setStatus(String status) {
        this.status = status;
    }

}

This is the rest controller I've.

@RequestMapping(value = "/user/all", method = RequestMethod.GET)
    public JsonNode getAllUsers(HttpServletRequest httpServletRequest) throws IOException {

        JSONObject response = new JSONObject();

        List<User> users = new ArrayList<>();

        try {
            users = userService.getAllUsers();
            if (users.size() > 0) {
                response = utility.createResponseArray(200, Keyword.SUCCESS, new JSONArray(utility.convertPOJOtoString(users)));
            } else {
                response = utility.createResponseArray(204, Keyword.NO_CONTENT, new JSONArray());
            }
        } catch (Exception e) {
            return objectMapper.readTree(utility.createResponse(500, Keyword.ERROR, e.toString()).toString());
        }

        return objectMapper.readTree(response.toString());
    }

So I'm getting data from this end point using service and repository. not attaching those code here.

this is the http-client.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { logging } from 'protractor';

export class User{
  constructor(
    public id:string,
    public firstName:string,
    public lastName:string,
    public email:string,
    public contact:string,
    public status:string,
  ){}
}

@Injectable({
  providedIn: 'root'
})
export class HttpClientService {

  constructor(private httpClient:HttpClient) { }

  getAllTheEmployees()
  {
    console.log("test call");
    return this.httpClient.get<User[]>('localhost:8080/cms/user/all');
  }
}

this is the user.component.ts

import { Component, OnInit } from '@angular/core';
import { HttpClientService } from '../service/http-client.service';

@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {

  users: string[];

  constructor(
    private httpClientService: HttpClientService
  ) { }

  ngOnInit() {
    this.httpClientService.getAllTheEmployees().subscribe(
      response => this.handleSuccessfulResponse(response),
    );
  }

  handleSuccessfulResponse(response) {
    this.users = response;
  }

}

this is the user.component.html

<table>
    <thead></thead>
    <tr>
        <th>Id</th>
        <th>First Name</th>
        <th>Last Name</th>
        <th>Email</th>
        <th>Contact</th>
        <th>Status</th>
    </tr>

    <tbody>
        <tr *ngFor="let user of users">
            <td>{{user.id}}</td>
            <td>{{user.firstName}}</td>
            <td>{{user.lastName}}</td>
            <td>{{user.email}}</td>
            <td>{{user.contact}}</td>
            <td>{{user.status}}</td>
        </tr>
    </tbody>
</table>

app-routing.module.ts

import { NgModule } from '@angular/core';
import { Routes, RouterModule } from '@angular/router';
import { UserComponent } from './user/user.component';

const routes: Routes = [
  {path:'allUsers',component:UserComponent},
];

@NgModule({
  imports: [RouterModule.forRoot(routes)],
  exports: [RouterModule]
})
export class AppRoutingModule { }

I'm getting data in postman using endpoint, but for some reasons data are not coming in angular. Please help me by pointing where am I doing wrong. I'm getting a blank page with header, not data. please let me know where am i doing wrong, would appreciate any sort of help.

回答1:

Make changes in your handleSuccessfulResponse

 handleSuccessfulResponse(response) {
    this.users = response.data;
  }

Async Pipe are used to bind async data in angular

ngOnInit() {
    this.httpClientService.getAllTheEmployees().pipe().subscribe(
      response => this.handleSuccessfulResponse(response),
    );
  }

In your html

<tbody>
    <tr *ngFor="let user of users| async ">
        <td>{{user.id}}</td>
        <td>{{user.firstName}}</td>
        <td>{{user.lastName}}</td>
        <td>{{user.email}}</td>
        <td>{{user.contact}}</td>
        <td>{{user.status}}</td>
    </tr>
</tbody>

In your HttpClientService change

  getAllTheUsers(): Observable<any> { 
    return this.httpclient.get("http://localhost:8080/cms/user/all");; 
     } 
  }