启用 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!');
}
);