Meenal
Meenal

Reputation: 153

How to fetch a particular field from HTTPResponse POST method in Angular 6

Can someone please help me out with the approach to display contractID in html page when I could see the response in Network Tab of browser as : http:localhost:8080/api -> {contractId: 70, contractName: "HealthPlan2",contractServiceList :....}. I am confused since I do not have explicit get method from Web API to fetch this data but I can see this response in my browser. Currently I am saving into the API using http.post(), I am totally unaware of this functionality of Angular. Someone please explain how it;s internally working and how can I fetch an auto-generated ID which is not the part of my post method. Any suggestion on Interceptor would be good.

In app.component.ts

createForm(data: any): FormGroup {
    return this.formBuilder.group({
      contractId: [data ? data.contractId : ''],
      contractName: [data ? data.contractName : '', Validators.required],
      contractServiceList: this.formBuilder.array(
             this.createContractService(data ? data.contractServiceList : null),this.arrayValidator()
              )
      });
  }
ngOnInit() {
     {
    this.addForm = this.createForm(null);
    //  this.addForm.get('contractName').valueChanges.subscribe(changes => { console.log(changes) } )
   // this.addForm.valueChanges.subscribe(changes => { console.log( '*', changes) } )
    }
  }
onSubmit() {
    this.submitted = true;
    this.successMessage = '';
    this.errorMessage = '';
    console.log(this.addForm.value);
    if (this.addForm.invalid) {
            return;
        }
        this.getByName;
    this.contractService.saveContract(this.addForm.value)
      .subscribe( data => {
        this.successMessage = 'Contract created successfully';
      });
  }

In app.component.html

 <table>
<thead></thead>
<tbody>
<tr>
  <td>
    <input type="text" name="contractId" ng-model="contractId" style="display: none;"/>
  </td>
   <td>
   <div class="form-group col-xs-6">
      <label for="contractName">Contract Name:</label>
      <input formControlName="contractName" placeholder="Contract Name" class="form-control" name="contractName" id="contractName">
   <!--  <div *ngIf="submitted && f.contractName.errors" class="invalid-feedback">
                            <div *ngIf="f.contractName.errors.required">Contract Name is required</div>
                        </div> -->
                    </div>
   </td>
   <td>
 <div class="form-group col-xs-6">
     <h4 style="margin-left:100px;">Penalty Conditions</h4>
    </div>
</td>  
</tr>
</tbody>
</table>
<div formArrayName="contractServiceList">
<div *ngFor="let items of contractList.controls; let i=index" 
            [formGroupName]="i">
<table>
<thead></thead>
<tbody>
<tr> 
<td>
    <div class="form-group col-xs-6">
      <label for="serviceId">Category Of Services:</label>
      <select id ="serviceId" [(ngModel)]="serviceId" formControlName="serviceId" name="serviceId" class="form-control">
    <option value="1">Emergency Room</option>
    <option value="2">OP Radiology</option>
</select>
      </div>
    </td>
<td>
 <div class="form-group col-xs-6">
      <label for="penaltyApplies">Penalty Applies:</label>
       <select id ="penaltyApplies" formControlName="penaltyApplies" name="penaltyApplies" class="form-control">
    <option>Y</option>
    <option>N</option>
</select>

.....

In service.ts

saveContract(contract: Contract) {
    return this.http.post(this.baseUrl, contract).pipe(map(res => res.json));
  }

Upvotes: 1

Views: 2166

Answers (2)

Amit Chigadani
Amit Chigadani

Reputation: 29775

From the chat section it was clear that OP is using Http. Instead you can use HttpClient for angular 4 and above, which comes from @angular/common/http

import { HttpClient } from '@angular/common/http'
export class ContractService { 
     constructor(private http: HttpClient) { } 
     ......
}

You may also have to import HttpClientModule in app module.

import { HttpClientModule } from '@angular/common/http';

@NgModule({
 imports: [
   HttpClientModule
 ],

And also you need not explicitly convert your resp to json with this, you already get json data by default which is converted by new angular HttpClient. So in your case you really do not need map also because you just want to return back to component

import { HttpClient } from '@angular/common/http'
import { catchError } from 'rxjs/operators';

export class ContractService { 
     constructor(private http: HttpClient) { } 

     saveContract(contract: Contract) {
        return this.http.post(this.baseUrl, contract).pipe(
          catchError(this.handleError));
     }
}

Upvotes: 1

Masso
Masso

Reputation: 56

Response of Post method returned as an observable in your saveContract function and also mapped to Json correctly. so you can subscribe to retrieve the fields you want.

inside your onSubmit() function:

 this.contractService.saveContract(this.addForm.value)
      .subscribe( (data:any) => {

       //here you can access contractID:
       this.contractIdShownInUI = data.contractID;  

       this.successMessage = 'Contract created successfully';
      });

Upvotes: 0

Related Questions