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

前端 未结 30 1444
无人共我
无人共我 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:36

    In addition to the missing @Injectable() decorator

    Missing @Injectable() decorator in abstract class produced the Can't resolve all parameters for service: (?) The decorator needs be present in MyService as well as in the derived class BaseService

    //abstract class
    @Injectable()
    abstract class BaseService { ... }
    
    //MyService    
    @Injectable()
    export class MyService extends BaseService {
    .....
    }
    
    0 讨论(0)
  • 2020-11-22 17:37

    For me, I got this error when I mistakenly disabled this import in the polyfills.ts file , you need to ensure it is imported to avoid that error.

    /** Evergreen browsers require these. **/
    // Used for reflect-metadata in JIT. If you use AOT (and only Angular decorators), you can remove.
    import 'core-js/es7/reflect';
    
    0 讨论(0)
  • 2020-11-22 17:38

    Import it from the file where it is declared directly instead of the barrel.

    I don't know what exactly causes the issue but I saw it mentioned several times (probably some kind of circular dependency).

    It should also be fixable by changing the order of the exports in the barrel (don't know details, but was mentioned as well)

    0 讨论(0)
  • 2020-11-22 17:38

    In my case passing wrong parameters to constructor generates this error, basic idea about this error is that you unknowingly passed some wrong args to any function.

    export class ProductComponent {
        productList: Array<Product>;
    
        constructor(productList:Product) { 
             // productList:Product this arg was causing error of unresolved parameters.
             this.productList = [];
        }
    }
    

    I solved this by just removing that argument.

    0 讨论(0)
  • 2020-11-22 17:41

    As already stated, the issue is caused by the export ordering within the barrel which is caused by circular dependencies.

    A more detailed explanation is here: https://stackoverflow.com/a/37907696/893630

    0 讨论(0)
  • 2020-11-22 17:42

    for me it was just lack of () in @Injectable. Proper is @Injectable()

    0 讨论(0)
提交回复
热议问题