码迷,mamicode.com
首页 > Web开发 > 详细

ng-http

时间:2020-01-22 12:52:00      阅读:122      评论:0      收藏:0      [点我收藏+]

标签:response   err   data   read   esc   ons   into   mon   pcl   

启用 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

标签:response   err   data   read   esc   ons   into   mon   pcl   

原文地址:https://www.cnblogs.com/ygjzs/p/12228104.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!