首页 > 解决方案 > 我无法访问角度服务中存储的(之前获取的)数据

问题描述

所以,我可能不太了解 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)

}

标签: javascriptangularfrontend

解决方案


要做到这一点,请按如下方式解决您的问题。

服务

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();
}

推荐阅读