http调用失败时如何通知转储组件?

时间:2018-06-21 08:44:16

标签: angular angular-components angular-event-emitter

目前,我有一个智能组件products.component.ts和一个转储组件products-create.component.ts。当用户提交创建按钮时,转储组件将事件发送给智能组件。

products.component.ts进行http调用以将产品保存在服务器中。现在我需要知道的是,如何通知转储组件服务调用成功或失败?转储组件在失败时应显示错误,在成功时应导航到列表组件。

2 个答案:

答案 0 :(得分:1)

那么您可以使用RXJS的SubejctBehaviorSubject来多播数据。
Example

更好的方法是使用shareReplay运算符为多个观察者共享一个http请求,并采取相应的行动。
您必须意识到http返回可观察到的寒冷,并且 当冷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

答案 1 :(得分:0)

您可以从OnChanges界面的ngOnChanges方法内进行操作:

基本上,您需要将一个属性从父组件传递到子组件,名为“ responseState”,如果此属性从父组件更改,则触发ngOnChanges方法,然后检查该属性值。

child.component.ts:

swift_mailer

在父组件中:

@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'
        */
   }
}