http调用失败时如何通知转储组件? [英] How to notify dump component when a http call is failed?
问题描述
目前我有一个智能组件 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
来多播数据.示例
Well you could use RXJS'S Subejct
or BehaviorSubject
to multicast the data.
Example
更好的方法是使用 shareReplay
操作符并采取相应措施.
你必须知道 http
返回一个冷的 observable 并且当一个冷的 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 and
When 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调用失败时如何通知转储组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!