ng g s services/http
app.module.ts
... @NgModule({ declarations: [ ... ], imports: [ ... HttpClientModule,//这个很重紧要,没有就会报错 ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }
services/http.service.ts
import { HttpClient } from '@angular/common/http'; import { Injectable } from '@angular/core'; @Injectable({ providedIn: 'root' }) export class HttpService { private apiUrl = "http://localhost:8888/test/1.json"; constructor(private http: HttpClient) { } public getData(params: any) { return this.http.get(this.apiUrl, { params }); } public postData(params: any) { return this.http.post(this.apiUrl, { params }); } }
app.component.ts
import { HttpService } from './services/http.service'; ... constructor( public http: HttpService ) { } ... ngOnInit() { this.http.getData({ param1: 1, param2: 2 }).subscribe(d => { console.log(d); }); this.http.postData({ param1: 1, param2: 2 }).subscribe(d => { console.log(d); }); }
最终呈现的效果是