angular - 如何在组件之间共享来自 http 响应的数据?
问题描述
我正在开发一个应用程序,它应该向第三个 API 发出 http 请求。当我进行身份验证过程时,Api 为我提供了一个密钥(它称为 clientid),我必须将其与其他数据一起发布到未来的 http 请求中。
所以情况是,在对 Api 进行身份验证后,当我想发出任何其他请求时,我必须发布我从身份验证响应中获取的 clientid。
我读到了父子关系(@input-@output),但我认为这没有帮助,因为应用程序会从不同的组件发出不同的请求,它们之间可能没有关系。
我的想法是,当我完成各个服务的身份验证过程时,我必须将此字段存储在某个地方,以便在我想从我需要的任何组件发出其他请求时可用。
我认为我需要类似单例方法的方法,但我不确定这种想法是否合适。
解决方案
您将需要一个发出请求并存储数据的服务。下面是一个简单服务的示例,它对一些字符串数组的数据发出 HTTP 请求。
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable, of, tap } from 'rxjs';
Injectable({
providedIn: 'root'
})
export class MyExampleService {
private myData: string[] = [];
constructor(private readonly http: HttpClient) { }
getData$(): Observable<string[]> {
//if we already got the data, just return that
if (this.myData.length > 0) {
return of(this.myData);
}
//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.myData = returnedData;
}));
}
}
然后在您的角度组件中,它们都可以以完全相同的方式请求数据,但只有首先执行此操作的组件才会实际发出 HTTP 请求,其他组件只会获取已缓存的数据。
import { Component, OnInit } from '@angular/core';
import { MyExampleService } from '../services/my-example.service';
@Component({
selector: 'app-my-example',
templateUrl: './my-example.component.html'
})
export class MyExampleComponent implements OnInit {
theData: string[] = [];
constructor(private readonly myExampleService: MyExampleService) {}
ngOnInit(): void {
//call the service
this.myExampleService.getData$()
.subscribe((data: string[]) => {
//when sucessful, data is returned here and you can do whatever with it
this.theData = data;
}, (err: Error) => {
//When unsuccessful, this will run
console.error('Something broke!', err);
});
}
}
推荐阅读
- dictionary - Flutter - 可滚动布局(带地图的表单)
- javascript - 如何为移动设备禁用我的 javascript
- sql - 仅输出行的超集
- angular - 在 Angular 6 中实现区域类型图表 Highcharts
- python - 带有标准输入和标准输出的子进程 Popen --- 总是挂断
- python - How to change background colour of Figure object in Tkinter
- c# - 使用“as”将对象转换为预期类型返回 null
- javascript - 代码匹配JS中3个元素的高度,这样对吗?
- android - 杀死android pie中的应用程序后Scanfilter不扫描?
- android - 无法通过意图将数组列表从一个活动传递到另一个活动