I'm trying to have multiple angular components subscribe to a single http service. he flow of events is: User clicks button in test-data.component.html > test-data.service makes POST request > subscription in test-data.component receives data AND parent.component.ts receives data. The issue is that parent.component.ts never recieves that new data from the POST. Do I need to notify the parent.component that changes happened in the service provider? Here are the relevant parts of the application:
parent.component.html
<div>
<app-test-data></app-test-data>
</div>
parent.component.ts
@Component({
selector: 'app-short-form',
templateUrl: './short-form.component.html',
styleUrls: ['./short-form.scss'],
providers:[ShortFormService, TestDataService]
})
constructor(
private testDataService: TestDataService,
) { }
ngOnInit() {
this.testDataService.getTestData()
.subscribe(
(event: HttpEvent<any>) => {
switch (event.type) {
case HttpEventType.Response:
console.log('😺 Done!', event.body);
}
},
(err: HttpErrorResponse) => {
if (err.error instanceof Error) {
console.log("Client-side error occured.");
} else {
console.log("Server-side error occured.");
}
}
)
}
test-data.component.html
<button m(click)="getTestData($event)" >Populate w/ match</button>
test-data.component.ts
@Component({
selector: 'app-test-data',
templateUrl: './test-data.component.html',
styleUrls: ['./test-data.component.scss'],
providers: [TestDataService]
})
constructor(
private testDataService: TestDataService,
) { }
getTestData(event){
event.preventDefault();
this.testDataService.getTestData()
.subscribe(
(event: HttpEvent<any>) => {
switch (event.type) {
case HttpEventType.Response:
console.log('😺 Done!', event.body);
}
},
(err: HttpErrorResponse) => {
if (err.error instanceof Error) {
console.log("Client-side error occured.");
} else {`enter code here`
console.log("Server-side error occured.");
}
}
)
}
test-data.service.ts
constructor(
private http:HttpClient
) { }
getTestData(): Observable<HttpEvent<any>> {
const req = new HttpRequest('POST', this.testDataUrl, {
reportProgress: true,
});
var result = this.http.request(req).share();
return result
behavioursubjectorreplaysubjectthat will notify the parent component. This is a classic case for you to use shared services to avoid event spaghetti or use ngrx . ngrx link shared services link