gpt4 book ai didi

javascript - 如何将数据从服务而不是 HttpClient 返回到组件

转载 作者:行者123 更新时间:2023-11-29 23:14:11 24 4
gpt4 key购买 nike

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

}

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

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。 使用 Promise。

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

关于javascript - 如何将数据从服务而不是 HttpClient 返回到组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53241889/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com