1. 导入

  1. # app.module.ts
  2. // angular 自带http请求
  3. import {HttpClientModule} from '@angular/common/http' //引入http请求
  4. @NgModule({
  5. imports: [
  6. HttpClientModule // 配置
  7. ],
  8. })

2. 构造函数中注册

  1. # app.component.ts
  2. import { Component } from '@angular/core';
  3. import {HttpClient} from "@angular/common/http" //导入http请求
  4. @Component({
  5. //根主键
  6. selector: 'app-root',
  7. templateUrl: './app.component.html',
  8. styleUrls: ['./app.component.css']
  9. })
  10. export class AppComponent {
  11. title = 'my-app';
  12. constructor(public http:HttpClient){} // 注册
  13. }

3. 数据请求

通过subscribe()请求

  1. # app.component.ts
  2. import { Component } from '@angular/core';
  3. import {HttpClient} from "@angular/common/http"
  4. @Component({
  5. //根主键
  6. selector: 'app-root',
  7. templateUrl: './app.component.html',
  8. styleUrls: ['./app.component.css']
  9. })
  10. export class AppComponent {
  11. title = 'my-app';
  12. constructor(public http:HttpClient){};
  13. ngOnInit(){
  14. this.http.get("http://localhost:8000/top250").subscribe(res =>{
  15. console.log(res);
  16. })
  17. }
  18. }