javascript - 无法使用订阅角度的结果
问题描述
我遵循本指南,并尝试在Unrelated Components: Sharing Data with a Service段落中做类似的事情
数据服务:
@Injectable()
export class MyDataService{
private messageSource = new BehaviorSubject(null);
currentMessage = this.messageSource.asObservable();
constructor(private http: HttpClient) {
setInterval(() => { this.changeMessage(this.resultFromRestCall()); }, 10 * 1000);
}
changeMessage(message: object) {
this.messageSource.next(message);
}
resultFromRestCall(){
const json;
this.http.get<object>(myApiUrl).subscribe(res =>
json['data'] = res['data'] //this is an example
);
return json;
}
零件:
export class MyComponent implements OnInit {
constructor(private dataservice: MyDataService) {}
ngOnInit() {
this.dataservice.currentMessage.subscribe(
message => {this.handleVarChange(message); }
);
}
handleVarChange(message) {
console.log(message.data);
}
handleVarChange
使用此代码,我在日志中得到“未定义”我没有调用
this.handleVarChange(message);
subscribe 我写了 console.log(message) 我得到了正确的结果。所以,我的问题是是否可以在我的组件的某些功能中使用来自数据服务的值。
提前致谢
解决方案
和:
resultFromRestCall(){
const json;
this.http.get<object>(myApiUrl).subscribe(res =>
// takes x amount of time to populate json
json['data'] = res['data'] //this is an example
);
// executed instantly after above request has been called
return json;
}
您在填充json
之前返回,因为请求是异步的。
相反,您可以将其翻转一下,然后resultFromRestCall()
先调用,当您收到响应时,再调用changeMessage()
:
setInterval(() => {
this.resultFromRestCall().subscribe((data) => {
this.changeMessage(data);
});
}, 10 * 1000);
其中resultFromRestCall
简单地返回一个可观察的:
resultFromRestCall(){
return this.http.get<object>(myApiUrl);
}
还记得clearInterval
在OnDestroy
!
演示
推荐阅读
- wordpress - Wordpress如何在执行cron之前注册全局对象,以便在cron作业期间可用?
- openapi - 如何在不使用 confluence 插件的情况下将 swagger/openapi yaml 文件包含到 doctoolchain 中并获得类似 swagger 的输出?
- python - Python - 具有多个 __init__() 的多重继承?
- vis.js-network - 在水平轴上集中节点
- facebook - Facebook 正在阻止来自我的服务器的请求
- javascript - 如何将提取的函数传递给自定义函数?
- python - 将连续的 SpcCy 实体提取到 Dataframe 中
- node.js - Jenkins Build Execute Shell - 文件权限被拒绝
- python - 为什么打印的 Inline::Python 函数重定向失败?
- c++ - 如何使用 for 循环在 C++ 中打印最少的数字?