启用 Http 服务

  • open the root AppModule,
  • import the HttpClientModule symbol from @angular/common/http,
  • add it to the @NgModule.imports array.
  1. // app.module.ts:
  2. import {NgModule} from '@angular/core';
  3. import {BrowserModule} from '@angular/platform-browser';
  4. // Import HttpClientModule from @angular/common/http
  5. import {HttpClientModule} from '@angular/common/http';
  6. @NgModule({
  7. imports: [
  8. BrowserModule,
  9. // Include it under 'imports' in your application module
  10. // after BrowserModule.
  11. HttpClientModule,
  12. ],
  13. })
  14. export class MyAppModule {}

发起一个 get 请求

  1. @Component(...)
  2. export class MyComponent implements OnInit {
  3. results: string[];
  4. // Inject HttpClient into your component or service.
  5. constructor(private http: HttpClient) {}
  6. ngOnInit(): void {
  7. // Make the HTTP request:
  8. this.http.get('/api/items').subscribe(data => {
  9. // Read the result field from the JSON response.
  10. this.results = data['results'];
  11. });
  12. }
  13. }

Reading the full response

  1. this.http
  2. .get('https://jsonplaceholder.typicode.com/posts/1', {observe: 'response'})
  3. .subscribe(res => {
  4. console.log(res)
  5. })

结果示例:

错误处理

  1. http
  2. .get('/api/items')
  3. .subscribe(
  4. // Successful responses call the first callback.
  5. data => {...},
  6. // Errors will call this callback instead:
  7. err => {
  8. console.log('Something went wrong!');
  9. }
  10. );