1.在app.module.ts中配置
import {HttpClientModule} from '@angular/common/http'
imports: [
BrowserModule,
AppRoutingModule,
HttpClientModule
],
2.在发送http请求的组件.ts文件中配置HttpClient,作为构造函数的参数设置
import { Component, OnInit } from '@angular/core';
import {HttpClient} from '@angular/common/http' //导入
...
export class ContentComponent implements OnInit {
constructor(public http:HttpClient) { } //配置
ngOnInit() {
}
}
3.发送请求
取数据时不能直接取到,要用 [ ]将要取的数据装起来
//.ts
import { Component, OnInit } from '@angular/core';
import {HttpClient} from '@angular/common/http'
...
export class ContentComponent implements OnInit {
public programs:any; //定义一个对象装数据
constructor(public http:HttpClient) { }
ngOnInit() {
var url:string="http://192.168.14.15:5000/dj/program?rid=336355127";
this.http.get(url).subscribe(res=>{
this.programs=res['programs']; //将取到的数据设置给定义的对象
})
}
}
4.渲染数据
//.html
<div *ngFor="let item of programs">
<p>{{item.name}}</p>
<img [src]="item.coverUrl" alt="">
</div>