Angular 4: When and why is @Inject is used in constructor?

后端 未结 3 817
孤街浪徒
孤街浪徒 2021-02-01 16:53

Problem Statment

I am learning Angular 4 and I have stumble upon a code where @Inject is being used in a constructor and I am

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-01 17:43

    IoC container in Angular uses the type declarations in the constructor to determine the objects to be injected to the constructor parameters.

    In your example, "public data: any" parameter could not be determined by its type declaration because it's defined as "any". In order to solve this problem, you have to use "@Inject(MAT_DIALOG_DATA)" decorator to inform the IoC container about the object that must be injected to "data" parameter.

    Also in your example, "@Inject" decorator is used with an InjectionToken to complicate things a little more :)

    An InjectionToken is actually a class which is used to name the objects to be used by IoC container to inject in to other classes. Normally you could use any classes name as a token for IoC injection (like "MatDialogRef" in your example) and this works fine. But when you start writing your UnitTests you realize that you need to use Mock objects instead of real objects to be injected into your classes and when you use real class names as your tokens, you could not do that.

    To solve this problem you could use Interfaces as token names and this is actually the right solution, but since JavaScript does not support interfaces you could not use Interface names as tokens, because transpiled code does not contain Interface definitions.

    As a result of all this, you need to use InjectionToken. An InjectionToken allows you to inject any object into your constructor. You just need to declare it in your modules and map to the real class that you want to be injected. This way you could use different classes for your production and test codes.

提交回复
热议问题