kuntal
kuntal

Reputation: 1591

Call Component Function from Service

I am trying to create a file upload component for my app .at the end when file upload complete I want to clear the files from uploaded,for that I write bellow function in file up-loader component .

  clearFileList(){
    this.uploadedFiles=[]
  }

and now I want to call this function from a service ,after that with the help of the service can reuse the method in other components .

How do i do this.

Upvotes: 0

Views: 437

Answers (1)

Przemyslaw Jan Beigert
Przemyslaw Jan Beigert

Reputation: 2486

Calling Component Function from Service it's not best pattern. I suggest something different. Service should contains public subject and component should subscribe to it:

class Service {
  public stream$ = new Subject<any>();

  method() {
    this.stream$.next(...);
  }

}

class Component {
  constructor(private service: Service) {}

  onInit() {
    this.service.stream$.subscribe(data => {
      this.method(data);
    }
  }
  method() {
    // do stuff;
  }

}

From service you can call method, that will call components method.

And of course remember about unsubscribe.

Upvotes: 1

Related Questions