angular - 在订阅方法函数之外获取变量数据
问题描述
我想创建一个从使用外部 API 的服务返回对象的函数。我无法让它工作。
GetMatchinfo (matchid : number ) : Match {
let aq :Match;
this.matchService.GetMatch(matchid).subscribe(
(Matchinfodata: Match)=>{
aq=Matchinfodata;
}
);
return aq;
}
解决方案
如果您从模板调用函数,只需将返回调用的位置移动到订阅块。或者如果你正在使用GetMatchInfo()
内部的一些其他功能,最好使用 observable 和 subject。
GetMatchInfo (matchid : number ) : Observable<Match> {
let aq = new Subject<Match>();
this.matchService.GetMatch(matchid).subscribe(
(Matchinfodata: Match)=>{
aq.next(Matchinfodata);
}
);
return aq.asObservable();
}
并订阅GetMatchInfo()
您需要的功能。
this.GetMatchInfo(id).subscribe(
(result) => {
console.log(result)
}
);
推荐阅读
- postgresql - 在 AWS Aurora 上还原快照时,如何修复“引擎不支持数据库集群”?
- python - 在 Python 中进行替换时充满 U+FFFD 的字符串
- twig - 数组的树枝检查元素在另一个数组中
- qliksense - 将一个表的多个列链接到另一个表中的单个列 - Qlik Sense
- javascript - Angular HTTP get 请求返回未定义
- java - Spring Batch 步骤未执行
- python - 我如何记录函数参数的字典键?
- java - 使用 Spring Boot RestController 下载多个 pdf 文件
- angular - 是否可以在 angular8 中开发自定义登录页面以通过 Azure Ad API 进行身份验证
- kubernetes - Terraform Kubernetes 部署与 pod 就绪门