栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何在Angle 2 Beta中的服务中有效使用Http Component?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何在Angle 2 Beta中的服务中有效使用Http Component?

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

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
指定的条件下(使用其构造函数)在其中注入对象
HTTP_PROVIDERS

import {bootstrap} from 'angular2/platform/browser'import {HTTP_PROVIDERS} from 'angular2/http';import {AppComponent} from './app.component'bootstrap(AppComponent, [  HTTP_PROVIDERS]);

然后可以将该服务注入到组件中,如下所述。不要忘记

providers
在组件列表中指定它。

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对象:

@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对象上预订回调,以便在响应存在时通知以更新组件的状态(与在Angular1中对promise所做的方式相同):

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
管道还可以用于隐式订阅可观察对象。这是使用它的方法。首先更新您的组件,以将可观察对象放入您要显示的属性中:

export class CompanyList implements onInit {  public companies: Company[];  constructor(private service: CompanyService) {    this.service = service;  }  ngonInit() {    this.companies = this.service.getCompanies();  }}

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

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


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/614756.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号