How to call component method from service? (angular2)

前端 未结 3 992
时光说笑
时光说笑 2020-11-30 01:18

I want to create service, which can interact with one component. All another components in my app, should be able to call this service, and this service should interact with

3条回答
  •  死守一世寂寞
    2020-11-30 01:47

    The question does not ask component interaction, it asks for calling a component method from a service.

    This simply can be achieved by injecting service to the component. Then define a method inside the service which takes a function as parameter. The method should save this function as a property of service and call it wherever it wants.

    // -------------------------------------------------------------------------------------
    // codes for component
    import { JustAService} from '../justAService.service';
    @Component({
      selector: 'app-cute-little',
      templateUrl: './cute-little.component.html',
      styleUrls: ['./cute-little.component.css']
    })
    export class CuteLittleComponent implements OnInit {
      s: JustAService;
      a: number = 10;
      constructor(theService: JustAService) {
        this.s = theService;
      }
    
      ngOnInit() {
        this.s.onSomethingHappended(this.doThis.bind(this));
      }
    
      doThis() {
        this.a++;
        console.log('yuppiiiii, ', this.a);
      }
    }
    // -------------------------------------------------------------------------------------
    // codes for service
    @Injectable({
      providedIn: 'root'
    })
    export class JustAService { 
      private myFunc: () => void;
      onSomethingHappended(fn: () => void) {
        this.myFunc = fn;
        // from now on, call myFunc wherever you want inside this service
      }
    }
    

提交回复
热议问题