我有一项服务,可以链接一组HTTP请求并返回产品列表。 这是我到目前为止的内容:
var books = {
"mainKey1": {
"History" : [
{"hai" : "hello"},
{"hai" : "bye"}
],
"tempKey" : "tempValue"
},
"mainKey2":{
"Number": "AD-3424",
"Number1": "AD-3424"
},
"temparr" : [
"ai",
"bi"
]
};
function replaceKeys(books,replacementkeys,newKeyJson) {
if(typeof books == 'object') {
newKeyJson = Object.keys(books).map((book) => {
if(typeof books[book] == 'object' || Array.isArray(books[book]) ) {
replaceKeys(books[book],replacementkeys,newKeyJson[book])
}
if(replacementKeys[book]) {
newKeyJson[replacementKeys[book]] = books[book];
delete newKeyJson[book];
}
})
}
else if(Array.isArray(books)) {
for( var i=0;i< books.length;i++) {
replaceKeys(books[i],replacementkeys,newKeyJson[i]);
}
}else if(typeof books == 'string') {
return;
}else {
return;
}
}
var replacementKeys = {"History" : "replaced History","hai" : "hi","Number" : "test","Number1" : "test2","mainKey1" :"sidekey","tempKey" : "realKey","mainKey2" :"side2"};
var newKeyJson = Object.assign({},books);
replaceKeys(books,replacementKeys,newKeyJson);
console.log(newKeyJson); //this will contain object with updated keys
在我的控制器中,我称之为:
listForDisplay(categoryId: string): Observable<any[]> {
if (!categoryId) return of([]);
return this.listFields(categoryId);
}
private listFields(categoryId: string): Observable<any[]> {
return this.fieldService.list(categoryId, true).pipe(
flatMap((fields: Field[]) => {
if (!fields) return of([]);
return this.listProducts(categoryId, fields);
}),
);
}
private listProducts(categoryId: string, fields: Field[]): Observable<any[]> {
return this.productService.listSpecificationProducts(categoryId).pipe(
flatMap((products: any[]) => {
if (!products) return of([]);
return this.mapVisibleFields(fields, products);
}),
);
}
private mapVisibleFields(fields: Field[], products: any[]): any[] {
console.log(products);
return this.productModelService.mapProductsWithSpecificationFields(fields, products);
}
问题在于第一部分的private getCategory() {
this.selectorSubscription = this.selectorService.category.subscribe(categoryId => {
this.products = [];
this.specificationService.listForDisplay(categoryId).subscribe((products: any[]) => {
console.log(products);
this.products = products;
});
});
}
返回一个数组。
控制器中的console.log
仅返回一个项目。...
赞:
我显然做错了什么。 有人可以帮忙吗?
答案 0 :(得分:0)
根据rxjs documentation,flatMap
将每个源值投影到一个Observable中,该值将合并到 输出可观察。
这就是为什么您的订阅被多次调用,每个值一次出现的原因。您确定需要flatMap吗?从您想做的事情看来,map会更合适。