我正在尝试从特定类调用服务,但由于某种原因它无法调用,即使我能够在其他类中使用它.我正在使用@Input
.我不知道这是否是造成问题的原因.
码:
import { Component, Input, OnInit } from '@angular/core'; import { Category } from './../Category'; import { CertService } from './../../shared/Service/cert.service'; @Component({ selector: 'app-cert-item', templateUrl: './cert-item.component.html' }) export class CertItemComponent implements OnInit { @Input() category: Category; @Input() categoryId: number; constructor( private certService: CertService //Console error "No provider for CertService!" ) { } ngOnInit() { console.log(this.certService.getCategories()); } }
app.module.ts
import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { FormsModule } from '@angular/forms'; import { HttpModule } from '@angular/http'; import { routing } from './app.routing'; import { ReactiveFormsModule } from '@angular/forms'; import { NgbModule } from '@ng-bootstrap/ng-bootstrap'; import { AppComponent } from './app.component'; import { HeaderComponent } from './shared/header.component'; import { DropdownDirective } from './dropdown.directive'; import { CertsComponent } from './certs/certs.component'; import { CertItemComponent } from './certs/cert-category/cert-item.component'; import { CertService } from './shared/service/cert.service'; import { HttpService } from './shared/Service/http.service'; import { LoginComponent } from './login/login.component'; @NgModule({ declarations: [ AppComponent, HeaderComponent, DropdownDirective, CertsComponent, CertItemComponent, LoginComponent ], imports: [ BrowserModule, FormsModule, HttpModule, routing, ReactiveFormsModule, NgbModule.forRoot() ], providers: [ CertService, HttpService ], bootstrap: [AppComponent] }) export class AppModule { }
我试图调用的服务类(示例)
import { Injectable } from '@angular/core'; import { Http, Response, Headers } from "@angular/http"; import { Observable } from "rxjs/Rx"; import 'rxjs/Rx'; @Injectable() export class CertService { constructor(private http: Http) { } getCategories() { return this.http.get('api/categories') .map((response: Response) => response.json()); } }
我也无法使用当前路线
this.subscription = this.route.params.subscribe( (params) => {... ...});
同样,上面的代码在其他类中工作正常但在此类中不行.
如果作为提供者提供了错误,则会发生这种情况.并且不太可能存在其他原因.
它在一个地方...shared/service/cert.service
,而在另一个地方...shared/Service/cert.service
.案件很重要.这取决于环境在构建过程中这些模块会发生什么,但这可能会导致错误,例如它们可能会重复并引用不同的对象.
要快速调试它,CertService
可以从两个文件中公开window.CertService1
,window.CertService2
并在控制台中进行比较,如果两者都定义相同.