After incorporating a new Service into an established Angular project using the command:
$ ng generate service utils/new
I decided to transfer certain methods from AppService
to NewService
.
Both services have identical constructors:
@Injectable({
providedIn: 'root'
})
export class AppService {
constructor(private http: HttpClient) {}
And
@Injectable({
providedIn: 'root'
})
export class NewService {
constructor(private http: HttpClient) { }
Subsequently, in a Component
, I attempted to utilize NewService
instead of AppService
(simply replacing AppService
with NewService
).
@Component({
//...
})
export class MyComponent implements OnInit {
constructor(private newService: NewService) {
newService.doSomething(...);
}
ngOnInit(): void {
}
The code compiled without any errors. However, at runtime, I encountered an error:
ERROR TypeError: n.appService is undefined
Struggling to comprehend the debugger's feedback, I took a guess and included private appService: AppService
in the constructor, even though it wasn't utilized anywhere in the MyComponent
code. This resulted in:
@Component({
//...
})
export class MyComponent implements OnInit {
constructor(private appService: AppService, private newService: NewService) {
newService.doSomething(...);
}
ngOnInit(): void {
}
Now, not only did the code compile successfully, but I also avoided any runtime errors.
This situation seems peculiar and counterintuitive to me. What key aspect did I overlook here?
Is there a configuration setting required to acknowledge the presence of NewService
?