Endlessly streaming data is requested through HTTP GET requests

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>

Answer №1

Follow these steps to subscribe to an Observable in MyComponent and return an Observable in your service:

export class MyService {

...

getData() {
    return this.http.get('someUrl')
        .map((res: Response) => res.json())
}

...
}

export class MyComponent {

...

ngOnInit() {
   this.fetchData();
}

fetchData() {
    this._myService.getData().subscribe(
        response => { this.data = response});
}
...
}

Incorporate the following code snippet into your template:

<tr *ngFor="let item of data">

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Challenges with saving a segment of an AJAX GET response (in JSON) as a string variable

I am facing an issue while attempting to save a section of the result obtained from a GET request through AJAX into a string variable. Essentially, my goal was to ensure that a specific function containing a GET request operation can return the outcome of ...

Checking for Webpack has begun in a separate process - not found

After working on my Angular2 + Typescript project with Webpack, I noticed a change in the bundling process. Previously, the console output would display three specific comments at the end: webpack: bundle is now VALID [default] Checking started in sepear ...

Is there a scalable alternative in MariaDB to JSON_TABLE in MYSQL/Oracle?

I'm struggling with unnesting a large array that is stored within a JSON document. In Oracle and MYSQL, I know I can achieve this using JSON_TABLE. Similarly, in SQL Server, I can utilize OPENJSON and in Postgres, I can use JSON(B)_array_elements. How ...

Exploring the depths of Typescript: Navigating through intricate mapping of keys and types in dynamic

Explaining this may be a bit tricky, but I'll start with stating my objective and then elaborate on the question as clearly as possible: Note: The version of typescript doesn't matter to me, any solution would be appreciated. interface Type {} ...

Simultaneously extracting information from 2 APIs with ForkJoin: Undefined Exception encountered

Seeking to retrieve data from 2 APIs using ForkJoin. Utilizing forkjoin for asynchronous data access. Successfully retrieved homeTeamName and awayTeamName, encountering error while accessing lines: core.js:1521 ERROR ReferenceError: allline is not define ...

Create a function that retrieves the value associated with a specific path within an object

I want to implement a basic utility function that can extract a specific path from an object like the following: interface Human { address: { city: { name: string; } } } const human: Human = { address: { city: { name: "Town"}}}; getIn< ...

Validation of Date in Angular 5 (with specified minimum and maximum dates)

Struggling to find a simple solution for this issue, I have a date input like the following: <input [(ngModel)]="toolDate" type="text" class="tool_input tool_input__date"> To control the input and restrict it to only accept dates, I am using . In m ...

Unexpected JSONP Parsing Issue Despite Correct JSON Data

I've implemented a Cross Domain AJAX request using JSONP, and it's working fine with CORS. However, I'm facing an issue with JSONP. I've checked other threads but couldn't find a solution for my case. Below is the code snippet: ...

Tips on storing JSON string array with multiple name/value pairs in distinct arrays using JavaScript

Below is a JSON string that I have: [ { "id" : "1", "name" : "name1" }, { "id" : "2", "name" : "name2" }, { "id" : "3", "name" : "name3" }, { "id" : "4", "name" : "name4" }, { "id" : "5", "name" : "name5" } ] Is there a way to split this data into two se ...

What are some ways to leverage a promise-returning callback function?

Here is a function that I have: export const paramsFactory = (params: paramsType) => { return ... } In a different component, the same function also contains await getPageInfo({ page: 1 }) after the return .... To make this work, I need to pass a cal ...

Why does my test in Angular 2 e2e protactor fail when I do not include browser.sleep()?

While working on my e2e tests, I encountered an issue with a custom select dropdown component I created. When trying to select items in the dropdown, I found that I had to use browser.sleep(...) in my test for it to pass. If I don't include this sleep ...

The form will not appear if there is no data bound to it

Can anyone help me with displaying the form even when the data is empty in my template? <form class="nobottommargin" *ngIf="details" [formGroup]="form" (ngSubmit)="onSubmit(form.value)" name="template-contactform"> <div class="col-sm-12 nopad ...

How to Load JSON Data Using D3 When Column Definitions are Separated

I'm currently working with d3.js and struggling to grasp how I can effectively load a JSON file representing a table that has separate column definitions. A typical JSON file, which I have no issue loading, might appear like this: [ { "id": 1, ...

Changing a portion of a string into a java.util.Date

After posting DateTime as JSON, it gets transformed into "/Date(1512839439513)/" I am looking to simply convert this format to java.util.Date "/Date(1512839439513)/" needs to be converted to java.util.Date My attempt so far: String date = finalObject.g ...

Having difficulty importing SVG files in TypeScript

When working with TypeScript (*.tsx) files, I encountered an issue where I couldn't import an SVG file using the following statement: import logo from './logo.svg'; The transpiler gave me this error message: [ts] cannot find module '. ...

What is the equivalent of specifying globalDevDependencies for npm @types packages in typings?

I am looking to update a project using tsc@2 and remove typings from my toolchain. Updating common dependencies is easy as they are listed in my typings.json file: "dependencies": { "bluebird": "registry:npm/bluebird#3.3.4+20160515010139", "lodash": ...

ES5 approach to Angular2 HTTP Providers (not TypeScript)

I'm currently developing an application and experimenting with Angular2 using ES5 JavaScript for fun. My main inquiry right now is how to access the Http service. Most of the available documentation is in TypeScript, which is not very helpful, or it p ...

Convert request query strings into JSON format

Requests will be coming in with a JSON object passed as a query string, but it won't have the same JSON structure. It will look something like this: http:/mysite/api/doSomething?name=name&address=address... I need to save this data as a String f ...

Scrolling content with the mdldialogservice in Angular2

I am utilizing the MdlDialogService to trigger a help dialog from my home component: launchHelpDialog(){ this.dialogService.showCustomDialog({ component: HelpComponent, animate: true, isModal: true, styles: {'widt ...

Angular input range slider that automatically rounds decimal values from the data bindings

I've implemented a range slider within an Angular form to capture and display recorded values. <input [formControlName]="object.id" [id]="object.id" type="range" [(ngModel)]="object.answer" [step]="objec ...