1.在app.module.ts中配置

  1. import {HttpClientModule} from '@angular/common/http'
  2. imports: [
  3. BrowserModule,
  4. AppRoutingModule,
  5. HttpClientModule
  6. ],

2.在发送http请求的组件.ts文件中配置HttpClient,作为构造函数的参数设置

  1. import { Component, OnInit } from '@angular/core';
  2. import {HttpClient} from '@angular/common/http' //导入
  3. ...
  4. export class ContentComponent implements OnInit {
  5. constructor(public http:HttpClient) { } //配置
  6. ngOnInit() {
  7. }
  8. }

3.发送请求

  • 取数据时不能直接取到,要用 [ ]将要取的数据装起来

    1. //.ts
    2. import { Component, OnInit } from '@angular/core';
    3. import {HttpClient} from '@angular/common/http'
    4. ...
    5. export class ContentComponent implements OnInit {
    6. public programs:any; //定义一个对象装数据
    7. constructor(public http:HttpClient) { }
    8. ngOnInit() {
    9. var url:string="http://192.168.14.15:5000/dj/program?rid=336355127";
    10. this.http.get(url).subscribe(res=>{
    11. this.programs=res['programs']; //将取到的数据设置给定义的对象
    12. })
    13. }
    14. }

    4.渲染数据

    1. //.html
    2. <div *ngFor="let item of programs">
    3. <p>{{item.name}}</p>
    4. <img [src]="item.coverUrl" alt="">
    5. </div>