BeauNut
BeauNut

Reputation: 69

How I can POST (http client) data from input and result data display to component in Angular?

I have problem with display data in component who I POST from input to server. In input I need enter companyId and after POST request server return specific data from company. In console I get response from server with data but I don't know how to display data by *ngFor loop in component.

Do you know how resolve this? Thank you for your help.

I expecting for display this data in component:

Name: IT company

City: Los Angeles

District: California

Id: 36786891 <- this is companyId

My code:

Response from server in console:

{
  city: "Los Angeles"
  district: "California"
  id: "36745687"
  name: "IT company"
}

model:

export class Fin {
  name: string;
  id: number;
  city: string;
  district: string;
}

service:

searchByCompanyId(companyId){
    return this.http.post(environment.appApiUrl + '/api/url', companyId, {responseType: 'text'});
  }

component.ts:

  finForm: FormGroup;
  finData: Fin[] = [];
  companyId: any;

  constructor(
    private apiService: ApiService,
  ) { }

  ngOnInit(): void {
    this.finForm = new FormGroup({
      companyId: new FormControl()
    });
  }

  submit() {
    this.apiService.searchByCompanyId(this.finForm.value).subscribe( response => {
      this.companyId = response;
      console.log(response);
    });
  }

component.html

<form fxLayout="column" fxLayoutGap="10px" [formGroup]="finForm" (submit)="submit()" class="form">
  <mat-form-field appearance="fill">
    <mat-label>ID</mat-label>
    <input matInput id="companyId" type="number" formControlName="companyId">
  </mat-form-field>

    <button mat-raised-button class="form-button" color="primary" type="submit">search</button>
</form>

<div *ngFor="let item of finData">
  <p>Meno: {{item.name}}</p>
  
  <p>ID: {{item.id}}</p>

  <p>District: {{item.district}}</p>
  
  <p>City: {{item.city}}</p>
</div>

Upvotes: 1

Views: 761

Answers (2)

BizzyBob
BizzyBob

Reputation: 14750

You have two problems:

  1. The variable name the template uses is called finData, but in your response you are populating companyId with the results.
  2. *ngFor needs an array of data, but your api response is a single item.

You can easily address these with one simple change:

 this.apiService.searchByCompanyId(this.finForm.value).subscribe(response => {
   this.finData = [response];  // <-----
   console.log(response);
 });

Here's a working StackBlitz

Upvotes: 1

tcrite
tcrite

Reputation: 553

change

this.companyId = response

to

this.finData = response

Upvotes: 0

Related Questions