I am facing an issue with my code where it requests data endlessly. The service I have retrieves data in the form of an Array of Objects. My intention is to handle all the HTTP requests, mapping, and subscriptions within the service itself. This is because I require the service to maintain the local array which is needed throughout the webpage. However, when I inspect the developer tools in the browser, the GET method keeps getting requested endlessly until the browser crashes.
It's important to note that the incoming data is not a "file.json" but a plain URL. In the backend, I employ the Jackson objectmapper to send the data as an Array with objects.
Interestingly, if I modify the code to have the service only send the `http.get('someUrl')` and perform the map and subscribe actions in the component, everything works fine. I also need assistance with the delete Data methods, as I couldn't get them to work even after modifying them to handle mapping and subscription in the component.
I'm hoping someone can spot any obvious errors!
The sections of code causing the endless loop:
MyService:
export class MyService {
private dummys: Array<Dummy>;
constructor(private http: Http) {
this.dummys = new Array<Dummy>();
}
getData() {
this.http.get('someUrl')
.map((res: Response) => res.json())
.subscribe(dummys => this.dummys = dummys);
return this.dummys;
}
saveData(dummy: Dummy) {
let body = JSON.stringify(dummy);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
this.http.get('someUrl', body, options)
.map((res: Response) => res.json())
.subscribe(dummy => this.dummys.push(dummy));
return this.dummys;
}
deleteData() {
let index = this.dummys.indexOf(dummy);
let body = JSON.stringify(dummy);
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
this.http.post('someUrl', body, options)
.map((res: Response) => res.json())
.subscribe(dummy => this.dummys = this.dummys.splice(index, 1);
return this.dummys;
}
}
MyComponent:
export class MyComponent {
name: string;
id: string;
date: string;
dummys: Array<Dummy>;
constructor(public _myService: MyService, public _router: Router) { }
getDatas() {
this._myService.getData()
}
saveDatas() {
let dummy = new Dummy(this.id, this.name, this.date)
this._myService.saveData(dummy)
this.name = '';
this._myService.getData();
}
deleteDatas(dummy) {
this._myService.deleteData(dummy);
this._myService.getData();
}
}
Template in MyComponent:
<form (submit)="saveDatas()">
<input required [(ngModel)]="name" placeholder="Add data">
</form>
<br>
<table>
<tr *ngFor="let data of getDatas()">
<td>{{data.name}}</td>
<td> {{data.date}} </td>
<td><button (click)="removeDatas(data)">Remove</button></td>
</tr>
</table>