问题描述
目前,我有一个智能组件products.component.ts
和一个转储组件products-create.component.ts
.当用户提交创建按钮时,转储组件将事件发送给智能组件.
Currently I have a smart component products.component.ts
and one dump component products-create.component.ts
. The dump component emits an event to the smart component when the user submits on create button.
products.component.ts
进行http
调用以将产品保存在服务器中.现在我需要知道的是,如何通知转储组件服务调用成功或失败?转储组件在失败时应显示错误,并在成功时导航到列表组件.
The products.component.ts
makes a http
call to save the product in the server. Now what i need to know is, how to notify the dump component that the service call is succeeded or failed? The dump component should show the error when failure and navigate to list component while success.
推荐答案
那么您可以使用RXJS的Subejct
或BehaviorSubject
来多播数据.
Example
Well you could use RXJS'S Subejct
or BehaviorSubject
to multicast the data.Example
更好的方法将是使用 shareReplay
运算符并采取相应措施.
您必须意识到http
返回可观察到的寒冷,并且当感冒observable
具有多个subscribers
时,将为每个subscriber
重新发射整个数据流.每个订户都变得独立,并获得自己的数据流
Better approach Would be to share a single http
request for multiple observers using shareReplay
operator and take action accordingly.
You must be aware of the fact that http
returns a cold observable andWhen a cold observable
has multiple subscribers
, the whole data stream is re-emitted for each subscriber
. Each subscriber becomes independent and gets its own stream of data
为避免HTTP请求重复,请使用shareReplay
运算符.
To Avoid Duplication of HTTP Requests shareReplay
Operator is used.
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import {Observable} from 'rxjs';
import {shareReplay,tap}from 'rxjs/operators';
@Injectable()
export class ShareService {
public response$:Observable<any>;
constructor(private httpc:HttpClient)
{
this.sendRequest();
}
public sendRequest()
{
this.response$= this.httpc.get('url').
pipe(tap(res=>{console.log('called');return res;}),shareReplay(1))
}
fetchData()
{
return this.response$;
}
}
products.component.ts:
constructor(service:ShareService)
{
service.fetchData().subscribe(result=>{
console.log(result);
})
products-create.component.ts:
constructor(service:ShareService)
{
service.fetchData().subscribe(result=>{
console.log(result);this.route.navigate(['listcomp'])
}
error=>{your logic}
)
Further Reading
这篇关于http调用失败时如何通知转储组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!