javascript - 我无法访问角度服务中存储的(之前获取的)数据
问题描述
所以,我可能不太了解 Observables。我有这样的片段,并希望通过 service.xml 中定义的函数(来自另一个组件)访问存储在此服务中的待办事项。不幸的是,我不知道该怎么做。
todos;
// fetching todos from api
fetchTodos() :Observable<Todo[]>{
return this.http.get<Todo[]>(api_url);
}
constructor(private http:HttpClient) {
this.fetchTodos()
.subscribe(data => this.todos = data)
}
解决方案
要做到这一点,请按如下方式解决您的问题。
服务
import { BehaviorSubject, Observable } from 'rxjs';
/* make the plain object a subject you can subscribe to */
todos: BehaviorSubject<Todo[]> = new BehaviorSubject<Todo[]>([]);
constructor(private http:HttpClient) {
/* get the data and put it in the subject */
/* every subscriber to this event will be updated */
this.fetchTodos().subscribe(data => this.todos.next(data));
}
getTodos(): Observable<Todo[]> {
return this.todos.asObservable();
}
// fetching todos from api
private fetchTodos(): Observable<Todo[]> {
return this.http.get<Todo[]>(api_url);
}
零件
constructor(private service: Service) {}
ngOnInit(): void {
/* here you go. this subscription gives you the current content of todos[] */
/* whenever it gets updated */
this.service.getTodos().subscribe(data => {
console.log(data);
});
}
请注意
当您离开组件时,应始终完成对 Observable 的订阅。在您的情况下,实现此目标的最佳方法是:
修改后的组件
import { Subscription } from 'rxjs';
private subscription: Subscription = new Subscription();
constructor(private service: Service) {}
ngOnInit(): void {
/* add each subscriber to the subscription */
this.subscription.add(
this.service.getTodos().subscribe(data => {
console.log(data);
});
);
}
ngOnDestroy(): void {
/* unsubscribe all subscribers at once */
this.subscription.unsubscribe();
}
推荐阅读
- elasticsearch - 使用 Elasticsearch 和 Kubernetes 进行数据存储的最佳实践
- git - cPanel“手动或拉动部署”仅工作一次并停止工作
- aws-glue-spark - 如何在 aws 胶水动态框架上创建过滤器以过滤掉一组(文字)值
- c# - 如何将 JSON 对象反序列化为具有可能是单个字符串或字符串数组的值的字典?
- batch-file - 下载具有错误 EOL 序列的文件
- arrays - 在 C 中制作随机整数数组时的奇怪问题
- node.js - 我从 Node.js 服务器调用 APNS 通知时遇到问题。这是我要回来的错误
- powerbi - COALESCE 和 DIVIDEs 交替结果有什么区别?
- c# - 将两个数字之间的所有数字相加
- python - Python:将循环变量相乘的 C 代码 for 循环