http

作者: Daeeman | 来源:发表于2020-04-29 20:01 被阅读0次
  • 启用 Http 服务
  • 发起一个 get 请求
  • 错误处理

启用 Http 服务

  • 打开根模块AppModule,
  • 导入 HttpClientModule模块从 @angular/common/http`,
  • 加入导入数组
// app.module.ts:
  import {NgModule} from '@angular/core';
  import {BrowserModule} from '@angular/platform-browser';
  import {HttpClientModule} from '@angular/common/http';
    @NgModule({
    imports: [
      BrowserModule,
      HttpClientModule,
    ],
  })
  export class MyAppModule {}

发起一个 get 请求

import { HttpClient} from '@angular/common/http';
  @Component(...)
  export class MyComponent implements OnInit {
      results: string[];
      // 注入组件
    constructor(private http: HttpClient) {}
      ngOnInit(): void {
     // 发起http
      this.http.get('/api/items').subscribe(data => {

        this.results = data['results'];
      });
    }
  }

Reading the full response

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

结果示例:

错误处理

http
.get('/api/items')
.subscribe(
  // Successful responses call the first callback.
  data => {...},
  // Errors will call this callback instead:
  err => {
    console.log('Something went wrong!');    
  }
);

相关文章

网友评论

      本文标题:http

      本文链接:https://www.haomeiwen.com/subject/kuanwhtx.html