如何在多个 Angular 组件之间共享 api 响应?
How to share api response between multiple Angular Components?
我正在努力思考并在 Angular 中使用 BehaviourSubject
(到目前为止运气不佳)。我的目标是在我的组件之间共享 api 请求响应。
这是我的项目的 stackblitz 设置:
https://stackblitz.com/edit/angular-ivy-3cql7e?file=src%2Fapp%2Fapicaller.service.ts
在 console/network 选项卡中,当前向 api 发出了三个请求。
我如何使用这些,以便只有一个 api 请求用于 component1
和 component2
为了直观地了解这个问题,这里有一张简图:
+-------------------+
| |
| apicaller.service | (api being called here)
| |
+-------------------+
+----------+ +-------------+
|component1| |component2 |
+----------+ +-------------+
Use only 1 api call
to get data across
x amount of components
您的服务方法 getData()
中的代码有误 - 它 returns 每次都有一个新的 http 请求,而不是共享一个。只需在服务中添加另一个可观察的 属性 即可解决此问题。添加 inside pipe shareReplay()
使这个 observable 在第一次订阅后变热,然后它将共享数据。像这样:
private readonly request = this._http
.get('https://swapi.dev/api/people/')
.pipe(
map((result) => result['results']),
shareReplay(),
);
getData() {
console.log(Math.random() * 100 + ' getData()');
// count api request
// return as array of objects
return this.request;
}
我正在努力思考并在 Angular 中使用 BehaviourSubject
(到目前为止运气不佳)。我的目标是在我的组件之间共享 api 请求响应。
这是我的项目的 stackblitz 设置:
https://stackblitz.com/edit/angular-ivy-3cql7e?file=src%2Fapp%2Fapicaller.service.ts
在 console/network 选项卡中,当前向 api 发出了三个请求。
我如何使用这些,以便只有一个 api 请求用于 component1
和 component2
为了直观地了解这个问题,这里有一张简图:
+-------------------+
| |
| apicaller.service | (api being called here)
| |
+-------------------+
+----------+ +-------------+
|component1| |component2 |
+----------+ +-------------+
Use only 1 api call
to get data across
x amount of components
您的服务方法 getData()
中的代码有误 - 它 returns 每次都有一个新的 http 请求,而不是共享一个。只需在服务中添加另一个可观察的 属性 即可解决此问题。添加 inside pipe shareReplay()
使这个 observable 在第一次订阅后变热,然后它将共享数据。像这样:
private readonly request = this._http
.get('https://swapi.dev/api/people/')
.pipe(
map((result) => result['results']),
shareReplay(),
);
getData() {
console.log(Math.random() * 100 + ' getData()');
// count api request
// return as array of objects
return this.request;
}