Angular service call function in component

前端 未结 2 1645
失恋的感觉
失恋的感觉 2020-12-10 09:43

So I know you can have two unrelated components communicate with each other via a service by having one component emit an event in the service and the other subscribe to it

2条回答
  •  天涯浪人
    2020-12-10 09:50

    The answer above is correct except that you don't bootstrap your service, you will add your service in your providers array in the app.module.

    @NgModule({
        declarations: [MyComponent],
        imports: [],
        providers: [MyService],
        bootstrap: [AppComponent]
    })
    

    Then you inject your service inside of the component

    import { Component } from '@angular/core'
    
    import { MyService } from './path/to/my.service'
    
    ...
    
    export class MyComponent {
    
        constructor(private myService:MyService){}
    
    }
    

提交回复
热议问题