在Angular 8中发出HTTP请求

时间:2019-06-06 08:28:16

标签: asp.net angular

我正在用角度发出http请求。但是值不会显示在网页中    而且我也在使用示例免费api-https://reqres.in/api    但这不会显示任何值。

这是我的组件。

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

      values: any;
      constructor(private http: HttpClient) { }

      ngOnInit() {
        this.getValues();
      }

      getValues() {
      return this.http.get<any>('https://reqres.in/api/users/2').subscribe(response => {this.values = response.any; });

      }

    }

这是component.html

 <ul>
    <li *ngFor="let value of values">
      {{ value.text }}
    </li>
  </ul>

2 个答案:

答案 0 :(得分:1)

如果获得单个记录,请不要使用ngFor。

将response.any更改为response.data,因为api返回JSON“数据”作为键而不是“ any”,然后在模板添加中,例如:

<ul>
    <li>
      {{ values.email}}
    </li>
  </ul>

ng供您使用,当api返回数据作为对象数组时。很好的解决方案是使用Postman,检查API返回的数据,了解JSON结构的样子。

答案 1 :(得分:1)

this.values = response.any是错误的,因为您的响应是具有属性data而非any的对象。

同样在此端点上,您得到的是一个用户,而不是一个用户集合,因此应将变量重命名为value而不是values

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

      value: any;
      constructor(private http: HttpClient) { }

      ngOnInit() {
        this.getValue();
      }

      getValue() {
      return this.http.get<any>('https://reqres.in/api/users/2').subscribe(response => {this.value = response.data; });

      }

    }

在HTML中,您可以使用json async pipe将数据显示为json

<div> {{ value | json}} </div>