Home > Mobile >  Display Post response data to template angular
Display Post response data to template angular

Time:02-24

Usually we call get request to display the data to client side. Is there any way to display the response that we get when we perform post request ?

Process: The user from client side post word and on the basis of word that is posted the post give response response as follows:

>0:{username:'patrick',userid:'3636363',position:'manager'}
>1:{username:'patrick1',userid:'3636364',position:'employee'}
>2:{username:'patrick2',userid:'3636365',position:'employee'}

I have used following way to post data My html:

<form #search="ngForm" (ngSubmit)="onSubmit(search.value)">
<input type="text" name ="name" ngModel placeholder="name">
<button type="submit"> Search</button>
</form>

my component.ts

export class HomeComponent{
url='https://localhost:7292/api/';

constructor (private http:HttpClient){}

  onSubmit(data:string){
this.http.post(this.Url 'Employee?name='data.name,data).subscribe((result)=>{
   console.log(result)
  })
}
In console for result it shows:
>0:{username:'patrick',userid:'3636363',position:'manager'}
>1:{username:'patrick1',userid:'3636364',position:'employee'}
>2:{username:'patrick2',userid:'3636365',position:'employee'}

So I want to display username,userid,position to the template. How do i display the post response ?

CodePudding user response:

You just need to store the response in a public or private class member like this:

export class HomeComponent{
constructor(){}

public result: string = '';

onSubmit(data:string){
this.http.post(this.Url 'Employee?name='data.name,data).subscribe((rslt:string)=>{
   this.result = rslt;
  })

}

and then in the template (HTML) you can access this property using the JSON pipe like this:

<div>{{result | json }}</div> /* Here you can see the whole result object */

<div>{{result.username}}</div> /*You can access an individual property like this */

CodePudding user response:

I think the optimal solution for this would be to create an object with the properties you will be displaying from the response, (userName, userId, position); When your post request returns, create the object with the values or set the object properties with said values (once validated) if already constructed. You can then use the object properties and angular's interpolation syntax to display the values to the user. You can also conditionally render the sections with ngIf directive and only display the values when they are set to something other than null/default values/safestate.

Edit. Also you should add a error catch to your http request to handle non success responses. You can add an error msg display here

  • Related