Angular 服务 return 可从回调函数中观察到

Angular service return observable from callback function

我正在使用 Angular 8.

在我的服务中,我使用了一个接受回调函数并在回调函数中赋值的库。

我的服务方式是

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

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

我想订阅这个raw()方法并在控制器

中得到res1的结果
constructor(
  private myS: MyService
) {}

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

但这不起作用。 如何 return 从回调函数中观察到?

您可以按照此 documentation 在 raw() 方法中创建一个新的 Observable 以将回调结果发送到您的 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();
    });
  });
}

您可以在 MyService 中创建一个 Subject,然后从您的组件订阅它。

managerData$ = new Subject<any>();

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

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

然后在组件中:

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

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

注意:如果需要退订,可以这样操作:

private managerDataSubscription: Subscription;

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

然后您可以在任何需要的地方调用 this.managerDataSubscription.unsubscribe();(例如 ngOnDestroy