简体   繁体   English

如何在angular2 NgModule中使用服务

[英]How to use service in angular2 NgModule

I have written I service and send get request.But working good with angular2 rc4.I am using angular2 rc5.It is giving error.I am using rc5 NgModule. 我已经写了我的服务并发送了get请求。但是与angular2 rc4一起工作良好。我正在使用angular2 rc5。它正在给出错误。我正在使用rc5 NgModule。

I am getting the following error.Please help me 我收到以下错误。请帮助我

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

在此处输入图片说明

gridview.service.ts 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 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 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)
            });
    }

}

import HttpClient in your gridview.module.ts 在您的gridview.module.ts中导入HttpClient

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

and define HttpClient in providers of gridview.module.ts 并在gridview.module.ts的提供程序中定义HttpClient

providers:    [ ItemService, HttpClient ]

See if this helps. 看看是否有帮助。

The service needs to be brought in at the component level, and should be instantiated in a constructor function as you have it. 该服务需要在组件级别引入,并应在constructor函数中实例化。 Below are the updates I believe you need to make to your code. 以下是我认为您需要对代码进行的更新。

gridview.module.ts 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 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)
            });
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM