为什么我在 subscribe 方法中未定义? 我正在尝试结合数据源。客户和类别。 我正在尝试根据类别集合中匹配的 CategoryId 来填充客户的类别属性。
constructor(private http: HttpClient) {}
ngOnInit() {
const custurmersWithCategory$ = combineLatest([
this.http
.get<ICustomer[]>(
"https://www.json-generator.com/api/json/get/cgqEBPcHtu?indent=4"
)
.pipe(delay(1000)),
this.http.get<ICategory[]>(
"https://www.mocky.io/v2/5db4195d300000520057b70b"
)
]).pipe(
map(([customers, categories]) => {
customers.map(
customer =>
({
...customer,
Category: categories.find(
c => customer.CategoryId === c.CategoryId
).category
} as ICustomer)
);
})
);
custurmersWithCategory$.subscribe(data => {
console.log(data);// why is this undefined?
});
}
最佳答案
您当前没有从 map
返回任何内容,因此您得到 undefined
。正如这里所解释的:https://stackoverflow.com/a/41743119/6294072你的代码翻译成这样:
function (foo) { bar; }
它根本不返回任何内容。所以添加
return customers.map( ...
它实际上会返回一些值。
<强> STACKBLITZ
根据评论,如果不想添加return
,您可以从map
内部删除大括号。
<强> STACKBLITZ
作为进一步的评论,就像我链接的答案中提到的那样,这与 rxjs map
无关,而是箭头函数的工作方式:)
关于javascript - RxJs 映射后未定义的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58570237/