2.http通讯

学习内容:
1.了解angular的Http服务
2.发送http请求
3.处理http响应
https://segmentfault.com/a/1190000010116848 http和httpClient的区别
异步的请求可以通过承诺,回调,响应式编程。默认用响应式编程。
https://segmentfault.com/a/1190000010259536#articleHeader1 新的写法
步骤1:ng g component product;
我们需要在 AppModule 中导入 HttpClientModule 模块;
第一种方法

export class HttpComponent implements OnInit {

  dataSource: Observable<any>; /*接收响应返回的流*/
  products: Array<any> = [];  /*模板做数据绑定*/
  constructor(private http: HttpClient) {
    this.dataSource = this.http.get('http://www.rvhqs.cn/api/country');
  } /*本地的datasourse和get返回的流挂在一起*/
  ngOnInit(): void {
  this.dataSource.subscribe(
    (data) => this.products = data   /*订阅到的数据传给我的product*/
  );
  }
} /*依赖注入*/

同上:
export class HttpComponent implements OnInit {
  products: Array<any> = [];  /*模板做数据绑定*/
  constructor(private http: HttpClient) {  } /*本地的datasourse和get返回的流挂在一起*/
  ngOnInit(): void {
    this.http.get('http://www.rvhqs.cn/api/country').subscribe(
      (data: Array<any>[]) => this.products = data   /*订阅到的数据传给我的product*/
    );
  }
} /*依赖注入*/




<p>
  商品信息
</p>
<ul>
  <li *ngFor="let product of products">
    {{product.name}}
  </li>
</ul>

异步:如果你不需要修改返回的数据直接使用 就可以用async

export class HttpComponent implements OnInit {

  products: Observable<any>;
  constructor(private http: HttpClient) {
    this.products = this.http.get('http://www.rvhqs.cn/api/country');
  }
  ngOnInit(): void {
  }
} /*依赖注入*/
<p>
  商品信息
</p>
<ul>
  <li *ngFor="let product of products | async" >
    {{product.name}}
  </li>
</ul>

例子演示:发送请求带上请求头

const headers = new HttpHeaders().set("X-CustomHeader", "custom header value");

this.courses$ = this.http
    .get(
        "/courses.json",
        {headers})
    .do(console.log)
    .map(data => _.values(data));

精确写法规范类型

product.ts

export class HttpComponent implements OnInit {
  results: Country[]; /*存返回的数据*/
  constructor(private http: HttpClient) {} /*依赖注入*/

  ngOnInit(): void {
    this.http.get('http://www.rvhqs.cn/api/country').subscribe((data: Country[]) => {
      this.results = data;
      console.log(this.results);
    });
  }
}
export interface Country {/*自定义类型*/
  id: number;
  name: string;
  name_native: string;
  minimum_age: number;
  default_unit: string;
  default_currency: number;
}

product.html

<p>
  商品信息
</p>
<ul>
  <li *ngFor="let result of results">
    {{result.name}}
  </li>
</ul>

image.png
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 136,092评论 19 139
  • Android 自定义View的各种姿势1 Activity的显示之ViewRootImpl详解 Activity...
    passiontim阅读 176,235评论 25 709
  • 文 | 一鸣 小林把沉沉的袋子放进共享单车的车篮子里,感觉两条手臂又酸又麻。可怜她一个小女生抱着将近二十斤的书走...
    一鸣阅读 4,417评论 28 59

友情链接更多精彩内容