0

I've added a new Service to an existing Angular project with:

$ ng generate service utils/new

Now I tried to move some methods from AppService to NewService.

Both services have the same constructor:

@Injectable({
  providedIn: 'root'
})
export class AppService {

  constructor(private http: HttpClient) {}

And

@Injectable({
  providedIn: 'root'
})
export class NewService {

  constructor(private http: HttpClient) { }

Now in a Component I try to use NewService instead of AppService (I simply replace AppService with NewService).

@Component({
//...
})
export class MyComponent implements OnInit {


  constructor(private newService: NewService) {
    newService.doSomething(...);
  }

  ngOnInit(): void {
  }

It compiles. But I get a runtime error: ERROR TypeError: n.appService is undefined

I could not understand what the debugger was saying so I made a guess: I added private appService: AppService to the constructor, although it is not being used at all in the code of MyComponent. So now I have this:

@Component({
//...
})
export class MyComponent implements OnInit {


  constructor(private appService: AppService, private newService: NewService) {
    newService.doSomething(...);
  }

  ngOnInit(): void {
  }

Now it compiles, and I also don't get any runtime error.

This looks strange and counterintuitive to me. What did I miss here?

Do I need some configuration setting to declare the existence of NewService?

8
  • Well, that's weird, can you replicate it? Commented May 28, 2022 at 15:10
  • I can try. Should Service classes be declared in module files? I've read in another answer that they don't have to if I use @Injectable({ providedIn: 'root' }) Commented May 28, 2022 at 15:21
  • If your service has the providedIn: 'root' parameter in the decorator you don't have to provide it to a module. When you will first use it in your class (in the constructor) the service will be created and the instance will be singleton. Commented May 28, 2022 at 15:32
  • angular.io/guide/singleton-services Commented May 28, 2022 at 15:35
  • Taking this info into account, if I never try in my code to initialize a reference to AppService - is it possible to have a reference to AppService as undefined in runtime? Commented May 28, 2022 at 15:41

1 Answer 1

1

This happened because in the html view of MyComponent was a reference to an AppService method. Strangely, the project still compiled and only failed at runtime.

Usually when I refer in html views to entities that are not recognized, I get a compilation error.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.