Angular 2 Beta - 向组件

时间:2016-01-04 14:01:43

标签: angular angular2-services

我是Angular2的新手,拥有Angular 1.3经验我正在尝试构建一个大型Angular 2应用程序,以获取各个功能的相应方式(模板语法,DI,路由,可观察)。 实际上我遇到的问题是在尝试创建一个单独的数据服务并放入所有HTTP调用并将其注入其他组件时。下面的代码我收到此错误EXCEPTION: No provider for ConnectionBackend!

此外,我还需要帮助删除仪表板摘要中的冗余导入。

DashboardHTTPSevice

import {Http, Response} from 'angular2/http'
import {Injectable} from 'angular2/core'

@Injectable()
export class DashboardHTTPSevice {

    http:Http;
    constructor(http:Http){
        this.http = http;
    }

    getSummary(){
        return this.http.get('api/dashboardSummary').map((res: Response) => res.json());
    }

}

DashboardSummary

import {Component} from 'angular2/core';
import {Http, HTTP_PROVIDERS} from 'angular2/http';
import 'rxjs/Rx' ;
import {DashboardHTTPSevice} from 'app/services/dashboardHTTPSevice';


@Component({
    selector: 'dashboard-summary',
    templateUrl: './app/admin/dashboard/summary/summary.component.html',
    styleUrls: ['./app/admin/dashboard/summary/summary.style.css'],
    viewProviders: [HTTP_PROVIDERS],
    providers : [DashboardHTTPSevice]

})

export class SummaryComponent { 

    public dashboardSummary;
    constructor (public http: Http , dataservice : DashboardHTTPSevice){

    dataservice.getSummary().
            .subscribe(summary => {
                console.log(summary.data);
                this.dashboardSummary = summary.data;
            });        
    }
}

Bootstrap

import {bootstrap}    from 'angular2/platform/browser';
import {ROUTER_PROVIDERS} from 'angular2/router';
import {AppComponent} from './app.component';
import {Http, HTTP_PROVIDERS} from 'angular2/http';
import {DashboardHTTPSevice} from 'app/services/dashboardHTTPSevice';


bootstrap(AppComponent , ROUTER_PROVIDERS , HTTP_PROVIDERS,DashboardHTTPSevice);

来源: https://github.com/sabha/angular2_store

演示: http://demoapp-angular2store.rhcloud.com/client/index.html

2 个答案:

答案 0 :(得分:3)

ROUTER_PROVIDERSHTTP_PROVIDERSDashboardHTTPService放入数组。

bootstrap(AppComponent , [ROUTER_PROVIDERS , HTTP_PROVIDERS, DashboardHTTPSevice]);

查看bootstrap函数here的签名:

答案 1 :(得分:1)

只想提供此答案的更新。

对于Angular 2 RC后发布版本,您需要导入HttpModule。