ng-http

Posted ygjzs

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了ng-http相关的知识,希望对你有一定的参考价值。

启用 Http 服务

  • open the root AppModule,
  • import the HttpClientModule symbol from @angular/common/http,
  • add it to the @NgModule.imports array.
// app.module.ts:
 
import {NgModule} from '@angular/core';
import {BrowserModule} from '@angular/platform-browser';
 
// Import HttpClientModule from @angular/common/http
import {HttpClientModule} from '@angular/common/http';
 
@NgModule({
  imports: [
    BrowserModule,
    // Include it under 'imports' in your application module
    // after BrowserModule.
    HttpClientModule,
  ],
})
export class MyAppModule {}

发起一个 get 请求

@Component(...)
export class MyComponent implements OnInit {
 
  results: string[];
 
  // Inject HttpClient into your component or service.
  constructor(private http: HttpClient) {}
 
  ngOnInit(): void {
    // Make the HTTP request:
    this.http.get('/api/items').subscribe(data => {
      // Read the result field from the JSON response.
      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!'); 
    }
  );

以上是关于ng-http的主要内容,如果未能解决你的问题,请参考以下文章

VSCode自定义代码片段——CSS选择器

谷歌浏览器调试jsp 引入代码片段,如何调试代码片段中的js

片段和活动之间的核心区别是啥?哪些代码可以写成片段?

VSCode自定义代码片段——.vue文件的模板

VSCode自定义代码片段6——CSS选择器

VSCode自定义代码片段——声明函数