【发布时间】:2020-12-02 02:02:52
【问题描述】:
我正在尝试了解从 api 存储(和更新)数据并在兄弟组件之间共享该数据的最佳方式。这是我尝试过的。
保存可观察对象
export class MyExampleService {
private data: Observable<any>;
constructor(private readonly http: HttpClient) { }
getData(): Observable<string[]> {
//if we already got the data, just return that
if (data) {
return data;
}
//if not, get the data
return this.http.get<string[]>('http://my-api.com/get-stuff')
.pipe(tap((returnedData: string[]) => {
//save the returned data so we can re-use it later without making more HTTP calls
this.data= returnedData;
}));
}
}
但是这种方法并不能真正满足我的需求,因为它不使用任何主题,并且我想在数据更改时告诉我的其他组件。
使用主题
export class MyExampleService {
private dataSbj: BehaviorSubject<any> = new BehaviorSubject(null);
readonly data$ = this.dataSbj.asObservable();
constructor(private readonly http: HttpClient) { }
getData(): Observable<string[]> {
if (dataSbj.getValue() === null) {
return this.http.get<string[]>('http://my-api.com/get-stuff')
.pipe(tap((returnedData: string[]) => {
//save the returned data so we can re-use it later without making more HTTP calls
this.dataSbj.next(returnedData);
}));
}
}
}
然后我只需在第一次订阅 getData 并订阅所有其他组件中的 data$ observable。 (在这种情况下,我有一个父组件和多个子路由,所以我会在父组件中订阅 getData() 并在所有子路由中订阅 data$。
最后一种方法可行,但我宁愿使用相同的函数来检索相同的数据,而不是通过订阅不同的 observables。
这被认为是一种好方法还是我可以做的更好?
【问题讨论】:
-
将数据存储在 cookie 中,在您的应用中使用身份验证和授权来限制数据
-
这听起来不对。我的意思是你可以做到,但我认为这不是最好的方法。在我的情况下,我更喜欢在内存中存储
标签: angular rxjs angular-services