'Service: typeof is not assignable to type 'Provider[]'
I am getting error: tried using like: "useClass: ApidataService" or "ApidataService" in providers and also remove public from the service constructor.
Failed to compile.
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'.
My service is:
import { Injectable } from '@angular/core';
@Injectable()
export class ApidataService {
public constructor() { }
cars = ['cars','bycycle','van'];
mydata(){
return "this is from apidata";
}
}
And 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 { }
Solution 1:[1]
Use useClass
to add class to provider
providers: [
{provide: APP_BASE_HREF, useValue: 'http://localhost:4200/', useClass: ApidataService}
],
Solution 2:[2]
The ApidataService has to be added as the second item in the providers list like this:
providers: [
{ provide: APP_BASE_HREF, useValue: 'http://localhost:4200/' },
{ provide: ApidataService, useClass: ApidataService }
],
or shorter:
providers: [
{ provide: APP_BASE_HREF, useValue: 'http://localhost:4200/' },
ApidataService
],
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Sachila Ranawaka |
Solution 2 | CsabaDev |