可观察模式的实例用法,subscribe

本文介绍如何在Angular应用中利用HTTP服务发起网络请求,并通过示例展示了如何获取JSON数据。文章详细解释了如何注入Http服务,发送GET请求,并将响应的数据转换为JSON格式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

  1. Description

    Performs http requests using XMLHttpRequest as the default backend.

    Http is available as an injectable class, with methods to perform http requests. Calling request returns an Observable which will emit a single Response when a response is received.

    HTTP是一个可注入类,具有执行HTTP请求的方法。调用请求返回一个可观察到的,当接收到响应时,它将发出一个响应

  2. import {Http, HTTP_PROVIDERS} from '@angular/http';
  3. import 'rxjs/add/operator/map'
  4. @Component({
  5. selector: 'http-app',
  6. viewProviders: [HTTP_PROVIDERS],
  7. templateUrl: 'people.html'
  8. })
  9. class PeopleComponent {
  10. constructor(http: Http) {
  11. http.get('people.json')
  12. // Call map on the response observable to get the parsed people object、
  13. // 在可观察到的人对象上观察到的响应调用映射
  14. .map(res => res.json())
  15. // Subscribe to the observable to get the parsed people object and attach it to the
  16. // component
  17. // 订阅可观察到的已解析的人对象并将其附加到组件
  18. .subscribe(people => this.people = people);
  19. }
  20. }
  21. Example

    http.get('people.json').subscribe((res:Response) => this.people = res.json());

    The default construct used to perform requests, XMLHttpRequest, is abstracted as a "Backend" ( XHRBackend in this case), which could be mocked with dependency injection by replacing the XHRBackend provider, as in the following example:




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值