【问题标题】:How to notify dump component when a http call is failed?http调用失败时如何通知转储组件?
【发布时间】:2018-11-30 12:39:48
【问题描述】:
目前我有一个智能组件products.component.ts 和一个转储组件products-create.component.ts。当用户提交创建按钮时,转储组件向智能组件发出事件。
products.component.ts 调用http 将产品保存在服务器中。现在我需要知道的是,如何通知转储组件服务调用成功或失败?转储组件应在失败时显示错误,并在成功时导航到列表组件。
【问题讨论】:
标签:
angular
angular-components
angular-event-emitter
【解决方案1】:
你可以使用 RXJS 的 Subejct 或 BehaviorSubject 来组播数据。
Example
更好的方法是使用 shareReplay 运算符为多个观察者共享一个 http 请求并采取相应的行动。
您必须意识到 http 返回一个冷的 observable 和
当一个冷observable 有多个subscribers 时,为每个subscriber 重新发出整个数据流。每个订阅者都变得独立并获得自己的数据流
为了避免重复 HTTP 请求,使用了 shareReplay 运算符。
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
【解决方案2】:
您可以在 OnChanges 接口的 ngOnChanges 方法中执行此操作:
基本上,你需要从父组件传递一个属性到子组件,命名为'responseState',如果这个属性从父组件改变,ngOnChanges方法被触发,然后你检查属性值。
child.component.ts:
@Component({...})
export class ChildComponent implements OnChanges {
@Input() responseState: boolean;
// this method is triggered when the Input properties changed.
ngOnChanges() {
if(responseState) {
// successful request
}else {
// failed request
}
}
}
在父组件中:
@Component({...})
export class ParentComponent {
responseState = undefined;
doRequest() {
/**
* If the request is failed,
* set 'this.responseState = false'
*
* if the request is successful
* set 'this.responseState = true'
*/
}
}
父模板:
...
<child-component
[responseState]='responseState'
> </child-component>
...