I\'ve built a basic app in Angular, but I have encountered a strange issue where I cannot inject a service into one of my components. It injects fine into any of the three o
Removing parameters from injectable constructor() method solved it for my case.
In my case it was a circular reference. I had MyService calling Myservice2 And MyService2 calling MyService.
Not good :(
In my case, the reason was the following:
As a consequence, when trying to create an object A, the default constructor failed. I have no idea why this wasn't a compile error.
I got it fixed by simply adding a constructor in A, which correctly called B's constructor.
In addition to the previous answers given, it seems this error is thrown as well when your injectable service is missing the actual @Injectable()
decorator. So before you debug the cyclic dependency thing and the order of your imports/exports, do a simple check whether your service actually has @Injectable()
defined.
This applies to the current Angular latest, Angular 2.1.0.
I opened an issue on this matter.
Gotcha!
If none of the above answers helped you, maybe you are importing some element from the same file where a component is injecting the service.
I explain better:
This is the service file:
// your-service-file.ts
import { helloWorld } from 'your-component-file.ts'
@Injectable()
export class CustomService() {
helloWorld()
}
This is the component file:
@Component({..})
export class CustomComponent {
constructor(service: CustomService) { }
}
export function helloWorld() {
console.log('hello world');
}
So it causes problems even if the symbol isn't inside the same component, but just inside the same file. Move the symbol (it can be a function, a constant, a class and so on...) elsewhere and the error will fade away
In my case I was trying to extend "NativeDateAdapter
" in order to override "format(date: Date, displayFormat: Object)
" method.
In AngularMaterial-2 DatePicker .
So basically I forgot to add @Injectable
anotation.
After I add this to my "CustomDateAdapter" class:
@Injectable({
providedIn: 'root'
})
Error has gone.