如何在angular2 NgModule中使用服务

时间:2016-10-15 10:00:22

标签: angular typescript

我写过我服务并发送get request.But与angular2 rc4工作正常。我正在使用angular2 rc5。它正在给出错误。我正在使用rc5 NgModule。

我收到以下错误。请帮助我

"Error: DI Exception↵ originalStack:
"Error: DI Exception↵    at NoProviderError.BaseException [as constructor]

enter image description here

gridview.service.ts

import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { HTTP_PROVIDERS } from '@angular/http';
import { HttpClient } from '../../shared/http/base.http';
import { URL_CONFIG } from '../../base/app.config';

import 'rxjs/add/operator/map';

@Injectable()
export class ItemService {

  constructor (private httpClient: HttpClient) {
    this.loadItems();
  }


  loadItems() {
     return this.httpClient.get('url')
      .map(res => res.json());
  }
}

gridview.module.ts

import { NgModule }           from '@angular/core';
import { disableDeprecatedForms, provideForms } from '@angular/forms/index';
import { CommonModule }       from '@angular/common';
import { bootstrap } from '@angular/platform-browser-dynamic';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule }        from '@angular/forms';
import { routing } from './gridview.routes'
import { GridViewComponent } from './gridview.component'
import { HttpClient } from '../../shared/http/base.http';
import { ItemService } from './gridview.service'
import { HTTP_PROVIDERS, HttpModule } from '@angular/http';
import { EventService } from '../../shared/service/event-service';
import {RouterModule, provideRouter} from "@angular/router";
import { URL_CONFIG } from '../../base/app.config';


@NgModule({
  imports:      [ BrowserModule,CommonModule, FormsModule,HttpModule,routing ],
  declarations: [ GridViewComponent,],
  exports:      [ GridViewComponent ],
  providers:    [ ItemService ]
})
export class GridviewModule { }

gridview.component.ts

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
 import { ItemService } from './gridview.service';
import { FieldFilter } from '../../shared/pipes/fieldfilter.pipe';
import { ROUTER_DIRECTIVES } from '@angular/router';
import { GridviewModule } from './gridview.module'

@Component({
    moduleId: module.id,
    selector: 'blank-page',
    templateUrl: 'gridview.component.html',
    styleUrls: ['gridview.component.css'],
    encapsulation: ViewEncapsulation.None,
    directives: [ ROUTER_DIRECTIVES ]
})

export class GridViewComponent implements OnInit {
    items:string[] = [];

    constructor(private itemService:ItemService) {
        // breaks when removed from here. 
        // Also breaks when declared as a class variable
    }

    ngOnInit() {
        this.itemService.loadItems()
            .subscribe((resp) => {
                this.items = resp.data;
                console.log("This is NgModule Data",this.items)
            });
    }

}

2 个答案:

答案 0 :(得分:1)

在gridview.module.ts中导入HttpClient

import { HttpClient } from '../../shared/http/base.http';

并在gridview.module.ts

的提供程序中定义HttpClient
providers:    [ ItemService, HttpClient ]

看看这是否有帮助。

答案 1 :(得分:1)

服务需要在组件级别引入,并且应该在constructor函数中实例化。以下是我认为您需要对代码进行的更新。

gridview.module.ts

import { NgModule }           from '@angular/core';
import { disableDeprecatedForms, provideForms } from '@angular/forms/index';
import { CommonModule }       from '@angular/common';
import { bootstrap }          from '@angular/platform-browser-dynamic';
import { BrowserModule }      from '@angular/platform-browser';
import { FormsModule }        from '@angular/forms';
import { routing }            from './gridview.routes'
import { GridViewComponent }  from './gridview.component'
import { HttpClient }         from '../../shared/http/base.http';
import { HTTP_PROVIDERS, HttpModule } from '@angular/http';
import {RouterModule, provideRouter} from "@angular/router";
import { URL_CONFIG }         from '../../base/app.config';


@NgModule({
  imports:      [ BrowserModule, CommonModule, FormsModule, HttpModule, routing ],
  declarations: [ GridViewComponent ],
  exports:      [ GridViewComponent ]
})
export class GridviewModule { }

gridview.component.ts

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { ItemService }       from './gridview.service';
import { FieldFilter }       from '../../shared/pipes/fieldfilter.pipe';
import { ROUTER_DIRECTIVES } from '@angular/router';
import { GridviewModule }    from './gridview.module'

@Component({
    moduleId: module.id,
    selector: 'blank-page',
    templateUrl: 'gridview.component.html',
    styleUrls: [ 'gridview.component.css' ],
    encapsulation: ViewEncapsulation.None,
    directives: [ ROUTER_DIRECTIVES ],
    providers: [ ItemService ]
})

export class GridViewComponent implements OnInit {
    items: string[] = [];

    constructor(private itemService:ItemService) {
        // breaks when removed from here. 
        // Also breaks when declared as a class variable
    }

    ngOnInit() {
        this.itemService.loadItems()
            .subscribe((resp) => {
                this.items = resp.data;
                console.log("This is NgModule Data",this.items)
            });
    }

}