javascript - Angular - 将数据订阅到可观察的返回未定义
问题描述
我正在做一个 Angular 项目。但是当我将数据订阅到 observable 时遇到问题返回未定义
我有一个从 HTTP 返回数据的服务方法。
public serviceMethod(): Observable<WordList[]> {
const url = `${this.baseUrl}/wordLists`;
return this.httpClient.get<GetResponseWordList>(url).pipe(
map(response => response._embedded.wordLists)
);
}
以及从服务中获取数据并将其分配给“数组”的组件方法
componentMethod() {
// get from the service
this.otherService.serviceMethod().subscribe(
data => {
this.array = data;
}
);
}
我在同一个文件中有另一种使用“数组”的方法
secondMethod(){
console.log(this.array)
}
最后,我有使用最后两种方法的主要方法。
mainMethodMethod(){
componentMethod();
secondMethod();
}
componentMethod() 首先运行。但是,总是得到数组的“未定义”值
一种解决方案是在订阅数据时将 secondMethod() 放入 componentMethod() 中。但我不想这样做,因为我需要使用循环,这将花费太长时间。
解决方案
我认为您应该澄清这部分问题:
“但我不想这样做,因为我需要使用循环,这将花费太长时间”
您需要使用什么循环?因为它的约束可能是问题的基础......
根据您的解释,我(至少)看到了这个解决方案:
componentMethod() {
// get from the service
return this.otherService.serviceMethod().pipe(
map(data => {
this.array = data;
})
);
}
mainMethodMethod(){
componentMethod().subscribe(() => {
secondMethod();
})
}
推荐阅读
- r - R - 获取由不同数据框中的值定义的一组列中的最高/最低值
- vb.net - 如何使用 VB.NET 在 Access Query 中保存、编辑和创建新记录
- sql - 运行存储过程后如何保留临时表?
- javascript - Angular - 如何将路由功能传递给子组件
- reactjs - useEffect 的一致返回
- python - pyenv .zshrc 在新设置上产生错误
- shopify - 结帐后存储客户付款信息
- python - 根据列表中的项目创建带有键的 Python 字典
- python - 如何在 O(n) 的列表中找到最小正整数?
- python - 如何从 Python Pandas Dataframe 中的 STRING 列中提取嵌套字典?