如何在 angular 2 beta 的服务中有效地使用 Http 组件? [英] How to Consume Http Component efficiently in a service in angular 2 beta?

查看:26
本文介绍了如何在 angular 2 beta 的服务中有效地使用 Http 组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 Angular 2-beta 并且我想使用 Http 组件.但是这里有一个严重的问题:

I'm trying to play with Angular 2-beta and I want to work with Http component. But there is a serious problem here:

我阅读了这个和我知道在 Angular 2(与 Angular 1 不同)中,Http 组件不是返回 Promise 的服务.它返回一个叫做 Observable 的东西.我们知道一个Component最好不要直接使用Http.高效的方式是做一个服务,负责消费Http.但是怎么样?!这应该在完成请求后返回一个承诺吗?(查看这里)

I read this and I know in Angular 2(Unlike Angular 1), Http component is not a service that returns a Promise. It returns something called Observable. We know that a Component is better not to use Http directly. Efficient way is to make a service that is responsible to consume Http. But how?! Should this after completing a request, return a promise? (look at here)

有意义吗?!

推荐答案

Angular 2 可以实现服务.它们仅对应于如下所述的可注入类.在这种情况下,这个类可以被注入到其他元素中,比如组件.

It's possible with Angular 2 to implement services. They simply correspond to injectable classes as described below. In this case this class can be injected into other elements like components.

import {Injectable} from 'angular2/core';
import {Http, Headers} from 'angular2/http';
import 'rxjs/add/operator/map';

@Injectable()
export class CompanyService {
  constructor(http:Http) {
    this.http = http;
  }
}

在引导应用程序的主要组件时,您可以在指定 HTTP_PROVIDERS 的条件下(使用其构造函数)在其中注入 Http 对象:

You can inject an Http object in it (using its constructor) at the condition you specified HTTP_PROVIDERS when bootstraping the main component of your application:

import {bootstrap} from 'angular2/platform/browser'
import {HTTP_PROVIDERS} from 'angular2/http';
import {AppComponent} from './app.component'

bootstrap(AppComponent, [
  HTTP_PROVIDERS
]);

然后可以将这个服务注入到一个组件中,如下所述.不要忘记在组件的 providers 列表中指定它.

This service can be then injected into a component, as described below. Don't forget to specify it within the providers list of the component.

import { Component, View, Inject } from 'angular2/core';
import { CompanyService } from './company-service';

@Component({
  selector: 'company-list',
  providers: [ CompanyService ],
  template: `
    (...)  `
})

export class CompanyList {
  constructor(private service: CompanyService) {
    this.service = service;
  }
}

然后,您可以利用服务中的 Http 对象实现一个方法,并返回与您的请求对应的 Observable 对象:

You can then implement a method leveraging the Http object in your service and return the Observable object corresponding to your request:

@Injectable()
export class CompanyService {
  constructor(http:Http) {
    this.http = http;
  }

  getCompanies() {
    return this.http.get('https://angular2.apispark.net/v1/companies/')
                  .map(res => res.json());
  }
}

然后组件可以调用这个 getCompanies 方法并订阅 Observable 对象上的回调,以便在有响应时通知更新组件的状态(与使用 promises 的方式相同)在 Angular1) 中:

The component can then call this getCompanies method and subscribe a callback on the Observable object to be notify when the response is there to update the state of the component (in the same way you did with promises in Angular1):

export class CompanyList implements OnInit {
  public companies: Company[];

  constructor(private service: CompanyService) {
    this.service = service;
  }

  ngOnInit() {
    this.service.getCompanies().subscribe(
      data => this.companies = data);
  }
}

编辑

正如 foxx 在他的评论中所建议的那样,async 管道也可用于隐式地订阅可观察对象.这是使用它的方法.首先更新你的组件,把可观察对象放在你要显示的属性中:

As foxx suggested in his comment, the async pipe could be also used to implicitly subscribe on the observable object. Here is the way to use it. First update your component to put the observable object in the attribute you want to display:

export class CompanyList implements OnInit {
  public companies: Company[];

  constructor(private service: CompanyService) {
    this.service = service;
  }

  ngOnInit() {
    this.companies = this.service.getCompanies();
  }
}

然后在模板中使用异步管道:

Use then the async pipe in your template:

@Component({
  selector: 'company-list',
  providers: [ CompanyService ],
  template: `
    <ul>
      <li *ngFor="#company of companies | async">{{company.name}}</li>
    </ul>
  `
})
export class CompanyList implements OnInit {
  (...)
}

这篇文章分两部分也可以提供更多细节:

This article in two parts could give more details as well:

希望对你有帮助蒂埃里

这篇关于如何在 angular 2 beta 的服务中有效地使用 Http 组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆