1.在app.module.ts中配置

  1. //Angular 的核心模块
  2. import { NgModule } from '@angular/core';
  3. // 浏览器解析模块
  4. import { BrowserModule } from '@angular/platform-browser';
  5. // App组件
  6. import { AppComponent } from './app.component';
  7. // http请求
  8. import {HttpClientModule} from '@angular/common/http'
  9. @NgModule({
  10. // 配置(声明)当前项目运行依赖的组件
  11. declarations: [
  12. AppComponent
  13. ],
  14. // 配置当前项目运行依赖的其他模块
  15. imports: [
  16. BrowserModule,
  17. HttpClientModule
  18. ],
  19. // 配置项目所需要的服务
  20. providers: [],
  21. // 指定应用的主视图
  22. bootstrap: [AppComponent]
  23. })
  24. // 通过导出AppModule这个模块,来启动应用
  25. export class AppModule { }

2.在app.component.ts中配置

  1. import { Component } from '@angular/core';
  2. import {HttpClient} from '@angular/common/http'
  3. @Component({
  4. selector: 'app-root',
  5. templateUrl: './app.component.html',
  6. styleUrls: ['./app.component.css']
  7. })
  8. export class AppComponent {
  9. title = 'my-app';
  10. lists:Array<number> = [1,2,3];
  11. constructor(public http:HttpClient){}
  12. handleClick():void{
  13. console.log(this.title)
  14. this.title = "change"
  15. }
  16. // 组件初始化的时候触发
  17. ngOnInit(){
  18. console.log("init")
  19. }
  20. }
  1. ngOnInit(){
  2. var url:string = "http://localhost:8000/top250";
  3. this.http.get(url).subscribe(res=>{
  4. console.log(res)
  5. })
  6. }