【问题标题】:Display Post response data to template angular显示发布响应数据到模板角度
【发布时间】:2022-11-10 12:06:26
【问题描述】:

通常我们调用get 请求将数据显示到客户端。当我们执行post request 时,有什么方法可以显示我们得到的响应?

过程: 来自客户端的用户发布词并根据发布的词post 给出响应响应如下:

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

我使用以下方式发布数据 我的html:

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

我的组件.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'}

所以我想在模板中显示username,userid,position。如何显示帖子回复?

【问题讨论】:

  • 您可以在问题中添加模板吗?

标签: angular typescript


【解决方案1】:

您只需将响应存储在公共或私有类成员中,如下所示:

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

}

然后在模板(HTML)中你可以像这样访问这个属性:

<div>{{result}}</div> /* Here you can see your result public variable of type string */

【讨论】:

  • 使用&lt;div&gt;{{result | json }}&lt;/div&gt; 我能够显示Json,但使用&lt;div&gt;{{result.username}}&lt;/div&gt; 访问单个属性什么也没显示。有什么我遗漏的或者我需要使用 ngif 来获取单个属性,因为响应在数组中并且它有大约 50 个数组数据。
  • *ngFor 是你的朋友..
【解决方案2】:

我认为对此的最佳解决方案是创建一个具有您将从响应中显示的属性的对象,(用户名、用户名、位置); 当您的发布请求返回时,使用这些值创建对象或使用所述值(一旦验证)设置对象属性(如果已经构建)。然后,您可以使用对象属性和 angular 的插值语法向用户显示值。您还可以使用 ngIf 指令有条件地渲染这些部分,并且仅在它们设置为空值/默认值/安全状态以外的值时才显示这些值。

编辑。 此外,您应该在您的 http 请求中添加一个错误捕获以处理不成功的响应。您可以在此处添加错误消息显示

【讨论】:

    猜你喜欢
    • 2019-11-10
    • 2016-04-17
    • 1970-01-01
    • 2021-02-27
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多