问题
componentA has subscriber of myService getData observable. componentB has the button. I want that after pressing this button next operations will appear:
myService will make a call to the server and will get data;
subscriber of componentA will process this data.
I tried the folowing code:
(myService)
getData(): Observable<IData> {
return this.http.get<IData>(apiUrl);
}
(componentA)
ngOnInit() {
this.myService.getData().subscribe(response => console.log(response));
}
(componentB)
public onClick(): void {
this.myService.getData();
}
When I press the button in ComponentB, a subscriber in ComponentA does nothing. How to activate subscriber in ComponentA after button press in ComponentB?
回答1:
You haven't defined relationship bw two component A &B. And I think you want to subscribe to service in A when a button is clicked in B. If B is child of A then you can use EventEmitter in child to emit event on button click, handle it in parent and then subscribe in that handler but then you cannot subscribe in ngOnInit lifecycle hook in A(you can subscribe in handler only). A: Template
<app-bcomponent (dataEmmiter)="handler($event)"><app-bcomponent>
A:Ts:
handler(e){
this.myService.getData().subscribe(response => console.log(response));}
B: Ts
@Output
dataEmmiter: EventEmitter<any> = new EventEmitter<any>();
getData(): Observable<IData> {
this.dataEmmiter.emit(anydata);
return this.http.get<IData>(apiUrl).subscribe(data=>{
//Do what u want
});
}
回答2:
The problem is that you are creating a new observable instance in the onClick (comp B) handler that has nothing to do with the one created in ngOnInit (Comp A).
Do this instead in your service:
public data$: Observable<IData>;
constructor() {
this.data$ = this.http.get<IData>(apiUrl).pipe(
shareReplay(1)
);
}
In component B:
public onClick(): void {
this.myService.data$.subscribe(
// Any code to execute when data is received
);
}
Then wherever you want to access the fetched data use myService.data$. The shareReplay operator will ensure that the http fetch operation will only be executed once no matter how many times data$ is subscribed to.
回答3:
you can set emitter in in your service and when you press button in component B , emit data and use subscriber in component a for subscribe data from service;
it's something like this :
public dataEmmiter: EventEmitter<any> = new EventEmitter<any>();
getData(): Observable<IData> {
return this.http.get<IData>(apiUrl).subscribe(data=>{
this.dataEmmiter.emit(data);
});
}
component a
ngOnInit() {
this.myService.getData().subscribe(response => console.log(response));
}
来源:https://stackoverflow.com/questions/56714969/how-to-activate-rxjs-subscriber-in-one-component-from-another-angular-component