将可注入服务函数作为回调函数参数传递

问题描述 投票:0回答:1

我想要实现的是首先获取数据,然后获取同步详细信息来决定何时应该再次获取数据。在这里我省略了逻辑的细节,因为这不是问题的原因。

问题是当我尝试将可注入服务函数作为回调函数参数传递时。

执行时,它会显示:

ERROR Error: Cannot read properties of undefined (reading 'http')

这让我相信在我调用回调时 HttpClient 尚未注入。

将可注入服务函数作为回调函数参数传递是否不正确? 有什么办法可以克服这个问题吗?

Stackblitz 上的代码

export class DataComponent implements OnInit {
  constructor(
    private dataService: DataService,
    private syncService: SyncService
  ) {}

  ngOnInit(): void {
    this.getData().subscribe();
  }

  getData() {
    return this.dataService.getData().pipe(
      tap((res) => console.log('get first data', res)),
      switchMap(() =>
        this.syncService.getSync(this.dataService.getSyncDetails, this.getData)
      )
    );
  }
}
@Injectable({
  providedIn: 'root',
})
export class SyncService {
  constructor() {}

  getSync(syncService: Function, callbackService: Function): Observable<any> {
    console.log('getSync');
    return syncService().pipe(
      tap((res) => console.log('get sync data', res)),
      switchMap(() => callbackService())
    );
  }
}
@Injectable({
  providedIn: 'root',
})
export class DataService {
  constructor(private http: HttpClient) {}

  getData(): Observable<any> {
    console.log('getData');
    return this.http.get('https://reqres.in/api/users');
  }

  getSyncData(): Observable<any> {
    console.log('getSyncData');
    return this.http.get('https://regres.in/api/unknown/2');
  }
}
angular dependency-injection rxjs callback
1个回答
0
投票

您仅提供一个函数,它会切换函数的上下文。要保留服务上下文,您可以在传递函数时将函数绑定到服务。

getData() {
    return this.dataService.getData().pipe(
      tap((res) => console.log('get first data', res)),
      switchMap(() =>
        this.syncService.getSync(this.dataService.getSyncDetails.bind(this.dataService), this.getData)
      )
    );
  }
© www.soinside.com 2019 - 2024. All rights reserved.