Angular2 Exception: No provider for Service

前端 未结 2 1546
庸人自扰
庸人自扰 2020-12-22 08:24

I\'m unable to instantiate my application when I have the component which is nested under the root component providing a component which it uses in it\'s constr

2条回答
  •  梦毁少年i
    2020-12-22 09:19

    You can fix it by adding GrandChild to App's providers.

    However, I don't understand why you were annotating Child and GrandChild as @Component when you're using them as services. I guess this is what you actually wanted to do.

    @Injectable()
    export class GrandChild(){
      constructor () {
        this.hello = "hey!"
      }
    }
    
    @Injectable()
    export class Child {
        tire: string;
        constructor(public grandchild: GrandChild) {
            this.grandchild = grandchild;
        }
    }
    
    @Component({
        providers: [Child, GrandChild],
        template: `Everything rendered fine!`,
        selector: 'app'
    })
    export class App {
        thread: Thread;
        selected: boolean = false;
        kid: Child;
    
        constructor(public child: Child) {
            this.kid = child;
        }
    }
    

    See updated plnkr demo.

提交回复
热议问题