{"id":22903551,"url":"https://github.com/sawyerbutton/angular-httpclient-usage","last_synced_at":"2026-04-29T18:31:55.016Z","repository":{"id":120748070,"uuid":"152171219","full_name":"sawyerbutton/Angular-HttpClient-Usage","owner":"sawyerbutton","description":null,"archived":false,"fork":false,"pushed_at":"2018-10-09T02:38:43.000Z","size":79,"stargazers_count":0,"open_issues_count":0,"forks_count":0,"subscribers_count":2,"default_branch":"master","last_synced_at":"2025-04-01T07:26:59.470Z","etag":null,"topics":["angular","httpclient","tricks"],"latest_commit_sha":null,"homepage":null,"language":"TypeScript","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/sawyerbutton.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2018-10-09T01:49:30.000Z","updated_at":"2018-10-09T02:38:44.000Z","dependencies_parsed_at":"2023-07-07T23:05:54.813Z","dependency_job_id":null,"html_url":"https://github.com/sawyerbutton/Angular-HttpClient-Usage","commit_stats":null,"previous_names":[],"tags_count":0,"template":false,"template_full_name":null,"purl":"pkg:github/sawyerbutton/Angular-HttpClient-Usage","repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sawyerbutton%2FAngular-HttpClient-Usage","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sawyerbutton%2FAngular-HttpClient-Usage/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sawyerbutton%2FAngular-HttpClient-Usage/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sawyerbutton%2FAngular-HttpClient-Usage/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/sawyerbutton","download_url":"https://codeload.github.com/sawyerbutton/Angular-HttpClient-Usage/tar.gz/refs/heads/master","sbom_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/sawyerbutton%2FAngular-HttpClient-Usage/sbom","scorecard":null,"host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":286080680,"owners_count":32439159,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2026-04-29T18:12:22.909Z","status":"ssl_error","status_checked_at":"2026-04-29T18:11:33.322Z","response_time":110,"last_error":"SSL_connect returned=1 errno=0 peeraddr=140.82.121.5:443 state=error: unexpected eof while reading","robots_txt_status":"success","robots_txt_updated_at":"2025-07-24T06:49:26.215Z","robots_txt_url":"https://github.com/robots.txt","online":false,"can_crawl_api":true,"host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["angular","httpclient","tricks"],"created_at":"2024-12-14T02:37:46.986Z","updated_at":"2026-04-29T18:31:54.981Z","avatar_url":"https://github.com/sawyerbutton.png","language":"TypeScript","funding_links":[],"categories":[],"sub_categories":[],"readme":"# Angular-HttpClient-Usage\n\n## Angular HttpClient 八爪鱼\n\n\u003e HttpClient是Angular4.3版本之后替代原本Http模块的产物\n\n\u003e 在使用HttpClient之前需要先在`app.module.ts`文件中导入`HttpClientModule`\n\n```typescript\nimport { BrowserModule } from '@angular/platform-browser';\nimport { NgModule } from '@angular/core';\nimport { HttpClientModule} from '@angular/common/http';\nimport { AppComponent } from './app.component';\n\n@NgModule({\n  declarations: [\n    AppComponent\n  ],\n  imports: [\n    BrowserModule,\n    HttpClientModule\n  ],\n  providers: [],\n  bootstrap: [AppComponent]\n})\nexport class AppModule { }\n\n```\n\n\u003e 导入模块后即可在组建服务或指令中引用httpClient\n\n```typescript\nimport { Injectable } from '@angular/core';\n\nimport { HttpClient } from '@angular/common/http';\n\n@Injectable({\n  providedIn: 'root'\n})\nexport class HttpUsageService {\n  constructor(private http: HttpClient) {}\n}\n```\n\n### HttpClient的基本使用\n\n\u003e 撰写基本的`get,post,put,patch,delete`请求与使用Http模块无二\n\n\u003e HttpClient和HttpModule最大的区别在于 - 默认情况下返回的response就是JSON格式，因此不再需要显式解析response为JSON格式\n\n### 一个简单地get请求\n\n```typescript\n public basicGetUsage() {\n    this.http.get(this.url).subscribe(res =\u003e {\n      this.response = res;\n    });\n  }\n```\n\n\u003e 如果希望response以非JSON的格式返回数据，则可以通过`responseType`设定特定的response类别，比如`text`\n\n```typescript\npublic getUsageWithDifferentResType() {\n    this.http.get(this.url, {responseType: 'text'}).subscribe(res =\u003e {\n      this.response = res;\n    });\n  }\n```\n\n\u003e 同样也可以通过定义一个描述response的接口对接收的response进行类型检测\n\n```typescript\ninterface Post {\n  title: string;\n  body: string;\n}\n\npublic getUsageWithSpecificInterface() {\n    this.http.get\u003cPost\u003e(this.url).subscribe(res =\u003e {\n      this.postTitle = res.title;\n      this.postBody = res.body;\n    });\n  }\n```\n\n\u003e 默认情况下HttpClient将会返回`response的body`,通过传入一个对象设置名为`observe`的键值为`response`以获得完整的响应\n\n\u003e 当用来检测某些响应的请求头时将会很有用\n\n```typescript\npublic getUsageWithFullResponse() {\n    this.http.get\u003cPost\u003e(this.url, {observe: 'response'}).subscribe(res =\u003e {\n      this.Auth = res.headers.get('Authorization');\n      this.postTitle = res.body.title;\n    });\n  }\n```\n\n### Post,Put,Delete 请求和Get请求类似\n\n\u003e 一个简单地post请求\n\n```typescript\npublic basicPostUsage() {\n    this.http.post(this.url, this.payload).subscribe(res =\u003e {\n      console.log(res);\n    }, (err: HttpErrorResponse) =\u003e {\n      console.log(err.error);\n      console.log(err.name);\n      console.log(err.message);\n      console.log(err.status);\n    });\n  }\n```\n\n\u003e 值得注意的是HttpClient使用的Observable是`cold Observable`，在使用subscribe订阅Observable前无法获取response信息\n\n\u003e 请求的错误类型为HttpErrorResponse，其中包含错误名称，错误消息和服务器状态\n\n#### 设置请求头和查询参数\n\n\u003e 通过使用`headers`和`params`作为一个对象的key将其作为第三个参数传递到请求中可以实现向请求添加额外的请求头等信息\n\n```typescript\npublic putUsageWithOptions() {\n    this.http.put(this.url, this.payload, {\n        params: new HttpParams().set('id', '123'),\n        headers: new HttpHeaders().set('Authorization', 'some-token')\n      })\n      .subscribe(res =\u003e {\n        console.log(res);\n      });\n  }\n```\n\n\u003e 值得注意的是, 在使用`HttpParams`和`HttpHeaders`之前都需要将其从`@angular/common/http`中引入\n\n### HttpClient流程事件\n\n\u003e HttpClient包含`监听progress event`的能力\n\n\u003e 监听可以在任何类型的请求上完成，并在请求事件的生命周期期间提供不同的信息\n\n```typescript\npublic getDataWithProgressEvent() {\n    //  build a request object by creating an instance of the HttpRequest class with the reportProgress option\n    const request = new HttpRequest('GET', this.url, {\n      reportProgress: true\n    });\n    this.http.request(request).subscribe((event: HttpEvent\u003cany\u003e) =\u003e {\n      switch (event.type) {\n        // sent the http request\n        case HttpEventType.Sent:\n          console.log('Request sent');\n          break;\n          // The response status code and headers were received.\n        case HttpEventType.ResponseHeader:\n          console.log('Response header received');\n          break;\n          // starting downloading content\n        case HttpEventType.DownloadProgress:\n          const kbLoaded = Math.round(event.loaded / 1024);\n          console.log(`Download in progress ${ kbLoaded }Kb loaded`);\n          break;\n          // The full response including the body was received.\n        case HttpEventType.Response:\n          console.log('response done', event.body);\n          break;\n          // An upload progress event was received, which will use in post/put/delete/patch\n        case HttpEventType.UploadProgress:\n          const kbUploaded = Math.round(event.loaded / event.total);\n          console.log(`upload in progress ${kbUploaded}Kb Uploaded`);\n          break;\n        case HttpEventType.User:\n          console.log('A custom event from an interceptor or a backend');\n      }\n    });\n  }\n```\n\n\u003e 首先需要通过创建HttpRequest类的实例并使用reportProgress选项\n\n\u003e 其次订阅我们的请求对象以发起请求，并在请求的整个生命周期中监听不同的事件类型\n\n\u003e 我们可以根据事件类型做出应对的反应,事件类型包括Sent，UploadProgress，ResponseHeader，DownloadProgress，Response和User\n\n\u003e 在上述代码中，从GET响应中获取到目前为止下载的数据量，如果使用Post等请求时，还可以从响应中获取到目前为止的上传数据量\n\n\u003e 某种意义上提供一个progress bar展示上传 下载进度的方案\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsawyerbutton%2Fangular-httpclient-usage","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fsawyerbutton%2Fangular-httpclient-usage","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fsawyerbutton%2Fangular-httpclient-usage/lists"}