我希望能够重新初始化Observable对象。 我不知道“重新初始化”是否是相应的术语,但是我的意思是我想刷新数据
@Injectable({
providedIn: 'root',
})
export class MyService {
private url = 'http://mydummydomain.com/api/entries';
private data$: Observable<any>;
constructor(private http: HttpClient) {
this.data$ = this.http.get(this.url).pipe(
shareReplay(1)
);
}
getData(): Observable<any> {
return this.data$;
}
reloadData() {
// TODO:
// Refresh data from the url
// Theoretically this should be a function with no input parameters and no return value
}
}
谢谢
答案 0 :(得分:2)
尝试
refresh$ = new Subject<void>();
data$ = this.refresh$.pipe(startWith(null), switchMap(() => this.http.get(this.url)), shareReplay(1));
reloadData() {
refresh$.next();
}
答案 1 :(得分:0)
我认为BehaivorSubject可以解决您的问题而无需创建新的可观察的对象,但是我建议使用ngrx或mobx处理数据,这要方便得多。我无法理解为什么您将数据设置为私有并创建getter?在视图中使用public作为变量的正常做法。
@Injectable({
providedIn: 'root',
})
export class MyService {
private url = 'http://mydummydomain.com/api/entries';
public data$: BehaviorSubject<any> = new BehaviorSubject(null);
constructor(private http: HttpClient) {
this.http.get(this.url).pipe(
take(1)
).subscribe((data) => {
this.data$.next(data);
});
}
reloadData() {
this.http.get(this.url).pipe(
take(1)
).subscribe((data) => {
this.data$.next(data);
});
}
}
最好将带有API的逻辑移到服务中,可以在多个组件中使用数据,并且将数据存储在一个位置时可以更有效地使用它。