如何 return 从服务而不是 HttpClient 到组件的数据

How to return data from a service not a HttpClient to component

我有这项服务,我需要 return 将产品添加到我在这里不使用的组件 HttpClient 或 Observable,因为我不需要它们

export class StoreDataProvider {

  private _wooData: any;

  constructor() {
    this._wooData = Woo({
      url: 'http://example.com/',
      consumerKey: 'key here',
      consumerSecret: 'key here',
      wpAPI: true,
      version: 'wc/v3'
    });
  }

  getAllProducts() {
    return this._wooData.get('products', (err, data, res) => {
      return res 
    });
  }

}

上面的代码 return 是 headers,不是产品,但如果我在服务本身而不是 return 中控制产品,我会得到产品!代码将是这样的:

export class StoreDataProvider {

  private _wooData: any;

  constructor() {
    this._wooData = Woo({
      url: 'http://example.com/',
      consumerKey: 'key here',
      consumerSecret: 'key here',
      wpAPI: true,
      version: 'wc/v3'
    });
  }

  getAllProducts() {
    this._wooData.get('products', (err, data, res) => {
      console.log(res); 
    });
  }

}

组件中的代码只是 console.log( this._wooService.getAllProducts() ) 如果我在服务上控制台登录

那么我在这里错过了什么?

解决这个问题的方法有很多:

1。 使用 BehaviorSubject

import { BehaviorSubject } from 'rxjs';

export class StoreDataProvider {

  private _wooData: any;
  private wooData: BehaviorSubject<any> = new BehaviorSubject<any>(null);
  public wooData$ = this.wooData.asObservable();

  constructor() {
    this._wooData = Woo({...});
  }

  getAllProducts() {
    this._wooData.get('products', (err, data, res) => {
      this.wooData.next(res);
    });
  }

}

然后你可以像这样在你的组件中使用它:

constructor(private _wooService: WooService) {}

ngOnInit() {
  this._wooService.wooData$.subscribe(res => console.log(res));
  this._wooService.getAllProducts();
}

请注意,当我们用 null 初始化 BehaviorSubject 时,最初您会得到 null。但是一旦您调用 getAllProducts 并收到数据,您就会得到您的数据。

2。 使用承诺。

export class StoreDataProvider {

  private _wooData: any;

  constructor() {
    this._wooData = Woo({...});
  }

  getAllProducts(cb) {
    return new Promise((resolve, reject) => {
      this._wooData.get('products', (err, data, res) => {
        if(err) reject(err);
        else resolve(res);
      });
    });
  }

}

然后你可以像这样在你的组件中使用它:

constructor(private _wooService: WooService) {}

ngOnInit() {
  this._wooService.getAllProducts()
    .then((res) => console.log(res))
}

3。 使用回调

export class StoreDataProvider {

  private _wooData: any;

  constructor() {
    this._wooData = Woo({...});
  }

  getAllProducts(cb) {
    this._wooData.get('products', (err, data, res) => {
      cb(res);
    });
  }

}

然后你可以像这样在你的组件中使用它:

constructor(private _wooService: WooService) {}

ngOnInit() {
  this._wooService.getAllProducts((res) => console.log(res));
}