问题
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.
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.
回答1:
Well you could use RXJS'S Subejct
or BehaviorSubject
to multicast the data.
Example
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
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
回答2:
You can do it inside the ngOnChanges method from the OnChanges interface:
basically, you need to pass a property from the parent component to the child component, named 'responseState', if this property changed from the parent component, ngOnChanges method is triggered, then you check the property value.
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
}
}
}
in the parent component:
@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'
*/
}
}
parent template:
...
<child-component
[responseState]='responseState'
> </child-component>
...
来源:https://stackoverflow.com/questions/50964153/how-to-notify-dump-component-when-a-http-call-is-failed