我们有没有办法在其他组件中(任何时候(一次又一次地使用http响应,比如java中的session?
我正在调用Http请求,它为我提供了一个对象列表。我需要在另一个组件也相同
this.http.post(data,config);
我不想再打电话了。
我读过关于缓存的文章,但我认为缓存可以在同一个组件中实现,只是我不能在另一个组件中使用数据
您可以在服务中使用BehaviorSubject
并将响应保存在其中,要在任何组件中使用它,只需订阅行为主题:
public responseBehavior: BehaviorSubject<any> = new BehaviorSubject<any>(null);
简单地保存响应:
this.http.post(data,config).subscribe(data=> this.responseBehavior.next(data));
在其他组件中使用此响应:
this.responseService.responseBehavior.subscribe(response=> console.log(response));
为了实现这样的目标,我通常使用两种方法(由您选择(
- 使用共享服务
在这里,您将在服务本身内部进行订阅,并将响应存储在服务类中的一个变量中。现在,您只需要使用组件文件中的变量,如:
在役::this._your_httpCall.subscribe(response => this.response = response);
和,
在组件中:
constructor(private service:Service);
someMethod_or_ngOnInit() {
this.service.response // gives the value
}
- 使用
Behavior Subject
或Replay Subject
这是更好的方法,我建议这样做。
在役::
private response$: BehaviorSubject<any> = new BehaviorSubject<any>(null);
exposedResponse$ = this.response$.asObservable();
this._your_httpCall.subscribe(response => this.response$.next(response));
和,
在组件中:
constructor(private service:Service);
ngOnInit() {
this.service.exposedResponse$.subscribe(response=> console.log(response));
}
注:
我们创建了一个像exposedResponse$ = this.response$.asObservable();
这样的新变量,只是为了确保行为主体response$
对服务类保持私有,并且不会在类之外被访问。