-
Description
Performs http requests using
XMLHttpRequest
as the default backend.Http
is available as an injectable class, with methods to perform http requests. Callingrequest
returns anObservable
which will emit a singleResponse
when a response is received.
-
- import {Http, HTTP_PROVIDERS} from '@angular/http';
- import 'rxjs/add/operator/map'
- @Component({
- selector: 'http-app',
- viewProviders: [HTTP_PROVIDERS],
- templateUrl: 'people.html'
- })
- class PeopleComponent {
- constructor(http: Http) {
- http.get('people.json')
- // Call map on the response observable to get the parsed people object、
- // 在可观察到的人对象上观察到的响应调用映射
- .map(res => res.json())
- // Subscribe to the observable to get the parsed people object and attach it to the
- // component
- // 订阅可观察到的已解析的人对象并将其附加到组件
- .subscribe(people => this.people = people);
- }
- }
-
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 theXHRBackend
provider, as in the following example:
可观察模式的实例用法,subscribe
最新推荐文章于 2023-07-16 10:02:17 发布