我收到错误: 尝试在提供程序中使用“useClass:ApidataService”或“ApidataService”,并从服务构造函数中删除公共。
编译失败。
C:/wamp64/www/angular/project/src/app/app.module.ts (33,69): Argument of type '{ declarations: (typeof AppComponent | typeof ViewComponent | typeof AboutComponent | typeof News...' is not assignable to parameter of type 'NgModule'.
Types of property 'providers' are incompatible.
Type '{ provide: InjectionToken<string>; useValue: string; ApidataService: typeof ApidataService; }[]' is not assignable to type 'Provider[]'.
Type '{ provide: InjectionToken<string>; useValue: string; ApidataService: typeof ApidataService; }' is not assignable to type 'Provider'.
Object literal may only specify known properties, and 'ApidataService' does not exist in type 'Provider'.
我的服务是:
import { Injectable } from '@angular/core';
@Injectable()
export class ApidataService {
public constructor() { }
cars = ['cars','bycycle','van'];
mydata(){
return "this is from apidata";
}
}
还有app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { HttpModule } from '@angular/http';
import { AppComponent } from './app.component';
import { ViewComponent } from './view/view.component';
import { AboutComponent } from './about/about.component';
import { RouterModule, Routes} from '@angular/router';
import { NewsComponent } from './news/news.component';
import {APP_BASE_HREF} from '@angular/common';
import { FormsModule } from '@angular/forms'; //for 2way binding
//SERVICES SAMPLE
import {ApidataService} from './apidata.service';
@NgModule({
declarations: [
AppComponent,
ViewComponent,
AboutComponent,
NewsComponent
],
imports: [
HttpModule,
BrowserModule,
FormsModule,
RouterModule.forRoot([
{path:'About',component:AboutComponent},
{path:'News',component:NewsComponent}
])
],
providers: [
{provide: APP_BASE_HREF, useValue: 'http://localhost:4200/',ApidataService}
],
bootstrap: [AppComponent]
})
export class AppModule { }
使用
useClass
将类添加到提供者
providers: [
{provide: APP_BASE_HREF, useValue: 'http://localhost:4200/', useClass: ApidataService}
],
必须将 ApidataService 添加为提供商列表中的第二项,如下所示:
providers: [
{ provide: APP_BASE_HREF, useValue: 'http://localhost:4200/' },
{ provide: ApidataService, useClass: ApidataService }
],
或更短:
providers: [
{ provide: APP_BASE_HREF, useValue: 'http://localhost:4200/' },
ApidataService
],