Error when trying to inject a service into an angular component “EXCEPTION: Can't resolve all parameters for component”, why?

前端 未结 30 1974
无人共我
无人共我 2020-11-22 17:18

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

30条回答
  •  面向向阳花
    2020-11-22 17:43

    Although the ordering of exported classes from within barrels may have been mentioned, the following scenario may also produce the same effect.

    Suppose you have classes A, B, and C exported from within the same file where A depends on B and C:

    @Injectable()
    export class A {
        /** dependencies injected */
        constructor(private b: B, private c: C) {}
    }
    
    @Injectable()
    export class B {...}
    
    @Injectable()
    export class C {...}
    

    Since the dependent classes (i.e. in this case classes B and C) are not yet known to Angular, (probably at run-time during Angular's dependency injection process on class A) the error is raised.

    Solution

    The solution is to declare and export the dependent classes before the class where the DI is done.

    i.e. in the above case the class A is declared right after its dependencies are defined:

    @Injectable()
    export class B {...}
    
    @Injectable()
    export class C {...}
    
    @Injectable()
    export class A {
        /** dependencies injected */
        constructor(private b: B, private c: C) {}
    }
    

提交回复
热议问题