启用 Http 服务
打开AppModule
从 @angular/common/http导入 HttpClientModule
添加到 @NgModule 的 imports 数组
typescript
复制代码
// app.module.ts:
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
// 导入 HttpClientModule
import {HttpClientModule} from '@angular/common/http';
@NgModule({
imports: [
BrowserModule,
// 'imports' 添加 HttpClientModule 模块
HttpClientModule,
],
})
export class MyAppModule {}
发起一个 get 请求
typescript
复制代码
@Component(...)
export class MyComponent implements OnInit {
results: string[];
// 将HttpClient注入到组件或服务中
constructor(private http: HttpClient) {}
ngOnInit(): void {
// 发起 HTTP 请求
this.http.get('/api/items').subscribe(data => {
// 从JSON响应中读取结果字段
this.results = data['results'];
});
}
}
错误处理
typescript
复制代码
http
.get('/api/items')
.subscribe(
// Successful responses call the first callback.
data => {...},
// Errors will call this callback instead:
err => {
console.log('Something went wrong!');
}
);