Anuj TBE
Anuj TBE

Reputation: 9790

Angular service return observable from callback function

I'm using Angular 8.

In my service, I'm using a library which accepts callback function and gives value in the callback function.

My service method is

raw(qrInfo, res?): Observable<string> {

  return manager.getData(res.width, (res1) => {
    return of<string>(res1);
  });
}

I want to subscribe to this raw() method and get the result of res1 in the controller

constructor(
  private myS: MyService
) {}

data() {
  this.myS.raw(info, op).subscribe(res => {
    console.log(res);                              // Get value here
  }
}

But this is not working. How can I return observable from callback function?

Upvotes: 0

Views: 2896

Answers (2)

Dino
Dino

Reputation: 8292

You could create a Subject inside the MyService and then subscribe to it from your component.

managerData$ = new Subject<any>();

raw(qrInfo, res?): Observable<string> {

  manager.getData(res.width, (res1) => {
    this.managerData$.next(res1);
  });
}

And then in component:

constructor(
  private myS: MyService
) {
    this.myS.managerData$.subscribe((res) => { ... } );
  }

data() {
  this.myS.raw(info, op);
}

NOTE: If you need to unsubscribe from it, you can do it like this:

private managerDataSubscription: Subscription;

constructor(
  private myS: MyService
) {
    this.managerDataSubscription = this.myS.managerData$.subscribe((res) => { ... } );
  }

And then you can call this.managerDataSubscription.unsubscribe(); where ever you need (in ngOnDestroy for example)

Upvotes: 0

Martin Paucot
Martin Paucot

Reputation: 1251

You can create a new Observable inside your raw() method by following this documentation to emit the callback result into your Observable.

raw(qrInfo, res?): Observable<string> {
  /** Returns the freshly created Observable **/
  return Observable.create(function(observer) {
    /** Call your method with the callback **/
    manager.getData(res.width, (res1) => {
      /** Emit the callback response to the Observable **/
      observer.next(of<string>res1)
      /** Complete the Observable to close it **/
      observer.complete();
    });
  });
}

Upvotes: 3

Related Questions