如何从服务而不是HttpClient向组件返回数据

时间:2018-11-10 18:02:01

标签: javascript angular ionic3 angular-services

我有此服务,我需要将产品返回到我在这里不使用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 
    });
  }

}

上面的代码返回标头,而不是产品,但是如果我在服务本身内部对产品进行控制台而不是返回,我将获得产品!该代码将是这样的:

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 个答案:

答案 0 :(得分:1)

有很多解决方案:

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();
}

请注意,当我们使用BehaviorSubject初始化null时,最初会得到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));
}