我試圖從特定的類調用服務,但由於某種原因它無法調用,即使我可以使用它在其他類中。我正在使用@Input
。我不知道這是否會導致問題。Angular 2 - 沒有提供程序錯誤(儘管我已經添加了提供程序)
代碼:
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) => {...
...});
同樣,上面的代碼在其他類中正常工作,但在此類中不起作用。
請給[mcve]。該服務是否在相關的模塊級'providers'數組中? – jonrsharpe
@jonrsharpe - 該服務位於app.module.ts文件中的相關'providers:[]'中。它被其他類使用,但不能在這個類中使用。我假設其他一切(除了這個課程)都是有效的,因爲我之前使用過它們沒有任何問題。另外,我使用Visual Studio Code,它不會給我任何錯誤,我可以自動導入服務。只有當我在瀏覽器中運行它時纔會出現錯誤 – ToDo
是在聲明組件的同一模塊中提供的服務? –