Implementing HTTP GET and POST requests in Angular 2 allows for the functionality of displaying, adding, and deleting objects within a list

Hey there, I'm completely new to dealing with HTTP and fetching data from the server. I've been scouring through various tutorials, examples, and questions on different platforms, but unfortunately, I haven't been able to find exactly what I'm looking for. Most of the tutorials I came across only demonstrate how to retrieve and add data.

Based on those examples, I was able to successfully retrieve data:

Service:

getCases(){
    return this.http.get('someUrl');
}

Case component constructor:

this._service.getCases()
        .map((res: Response) => res.json())
        .subscribe(cases => this.cases = cases);

Adding cases:

Service:

public saveCase(case: case) {

    let body = JSON.stringify(case);
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    return this.http.post('someUrl', body, options)
        .map(this.extractData)
        .catch(this.handleError)
        .subscribe(case => this.cases.push(case));
}

Case Component:

saveCase() {
    let case = new Case(this.id, this.name, this.date)    
    this._service.saveCase(case);
    this.name = '';         
}

Although I've managed to retrieve data successfully and add new cases, I'm facing a challenge in getting the Array to update automatically when a new case is added. At the moment, the new case only shows up after a browser refresh.

My second issue involves allowing users to click on a case, which then routes them to a detailed page where they can add steps and feedback. The case object includes attributes like id, name, date, and an array of steps (currently empty). Each step object has an array of feedback, with each feedback object having two string attributes. When I try to click on a case, the case name doesn't get displayed on the detail page, and the button for adding steps doesn't seem to work. Prior to integrating HTTP into my code, everything was functioning as expected. The methods I'm using probably need some adjustments, but I'm unsure about what needs to be done. Here are the methods that might require attention:

Case Component:

gotoDetail(case: Case) {
    this._router.navigate(['CaseDetail', {"id": case.name}]);
}

Service:

public getById(id: string): Case {
    for (let case of this.cases) {
        if (case.id === id) {
            return case;
        }
    }
    return null;
}

Another issue is regarding the syntax for removing cases. I've tried several examples, including those suggested in the links provided by @shershen, but none seem to work for me. The original methods I have need to be adjusted to interact with HTTP:

Component:

removeSearchCase(case: Case) {
    this._service.removeCase(case);
}

Service:

public removeCase(value: Case): void {

    let index = this.cases.indexOf(value);
    this.cases.splice(index, 1);
}

Thus, the case removal process involves a post request.

Lastly, in terms of the backend setup, I only have three endpoints: getCases (GET), saveCase (also functions as updating a case) (POST), and removeCase (POST).

Answer №1

Without a demo sample, debugging can be challenging, but the detailed descriptions provided are helpful. Here are some suggestions to potentially resolve the issue and enhance the code structure:

  • Initially, consider moving request subscription/observing into the service methods. This will help in encapsulating the request handling logic within the service layer:

//service.ts
@Injectable()
export class service {
  getCases(){
    if (!this.request) {
      this.request = this.http.get('/assets/data.json')
        .map((response: Response) => response.json())
        .map((data: string[]) => {
          this.request = null;
          return this.names = data;
        });
    }
    return this.request;
  }
}
  • Another point to note is the creation of an instance of the service within the Component's constructor instead of using it as a static method of the service:

//component.ts
import {MyService} from 'PATH_TO_YOUR_SERVICE';

class CaseComponent {
  constructor(private _service : MyService){
    //other stuff..
  }
  getData(){
    this._service.getCases()
  }
}

Further references:

Answer №2

Incorporating your cases Array into the CaseComponent is a good idea:

case.component.ts:

cases: Case[];
constructor(private caseService: CaseService){}

getCases() {
  this.caseService.getCases()
        .subscribe(cases => this.cases = cases);
}

saveCase() {
  let newCase = new Case(this.id, this.name, this.date);
  this.caseService.saveCase(newCase)
        .subscribe(c => this.cases = [...this.cases, c]);
}

case.service.ts:

getCases() {
    return this.http.get(this.casesUrl)
                     .map(this.extractData)
                     .catch(this.handleError);
}

saveCase (c: Case) {
    let body = JSON.stringify({ c });
    let headers = new Headers({ 'Content-Type': 'application/json' });
    let options = new RequestOptions({ headers: headers });

    return this.http.post(this.casesUrl, body, options)
                    .map(this.extractData)
                    .catch(this.handleError);
}

Consider changing "name" to "id" in gotoDetail:

gotoDetail(c: Case) {
  this._router.navigate(['CaseDetail', {"id": c.id}]);
}

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

The production build for Angular 9 Keyvalues pipe fails to compile

After successfully running my app on the development server with ng serve, I encountered a failure when trying to build it for production. The error message that popped up was: ERROR in src/app/leaderboard/leaderboard.component.html(9,17): Argument of typ ...

The issue of SVG not displaying on Chrome has been observed in Angular 6

I am working on loading multiple widgets in Angular 6. I have created a loading symbol using SVG, and I am using the following logic to hide and show the loading div until all widgets are loaded. Interestingly, in Firefox, the loading SVG appears as expect ...

Issue encountered with dynamic ngStyle variable: ERROR Error: Unable to locate a supporting object 'ngStyleSmall'

I have defined two variables for ngstyle ngStyleSmall = { width: '150px !important', 'max-width': '150px', }; ngStylemedium = { width: '250px !important', 'max-width&apo ...

What reasons underlie the existence of various methods for importing Modules in JavaScript?

I'm confused about the distinctions when it comes to importing a JavaScript module in various ways such as: CommonJS ES5 ES6 NodeJS Typescript What is the reason for having multiple methods of importing JavaScript modules? Is the concept of a "modu ...

The base URL specified in the tsconfig file is causing the absolute path to malfunction

Displayed below is the layout of my folders on the left, along with a metro error in the terminal and my tsconfig.json configuration with baseUrl set to './src'. Additionally, I have included screenshots of my app.ts and MainTabs.ts for further c ...

Exploring the integration of multiple HTTP requests in Angular with the power of RxJS

Is there a way to make multiple HTTP calls simultaneously in an Angular service and then combine the responses into one object using RxJS? import { Injectable } from '@angular/core'; import { HttpClient } from '@angular/common/http'; im ...

Why is Angular ng-block-ui not functioning properly in Angular 7?

Within my app.module.ts file import { BlockUIModule } from 'ng-block-ui'; imports: [ BrowserModule, BlockUIModule.forRoot(), ] Inside the dashboard component: import { BlockUI, NgBlockUI } from 'ng-block-ui'; export class Da ...

Tips for implementing type safety in a generic class to verify that the response type aligns with the anticipated type in TypeScript

In TypeScript, I have created a QueryFactory class with two generic type parameters: TQuery and TResponse. My goal is to ensure type safety so that if the TResponse type does not match the expected response type of the TQuery type, the compiler will throw ...

What methods can be implemented to ensure uniform usage of a single library version among all developers?

Our team utilizes Angular and Visual Studio Code for development, while GitHub serves as our code repository. While this setup has been effective, we recently encountered an issue where one developer had a different version of a particular library. This di ...

Testing React Hook Form always returns false for the "isValid" property

When creating a registration modal screen, I encountered an issue with the isValid value when submitting the form. In my local environment (launched by npm start), the isValid value functions correctly without any issues. However, during unit testing us ...

Display your StencilJs component in a separate browser window

Looking for a solution to render a chat widget created with stenciljs in a new window using window.open. When the widget icon is clicked, a new window should open displaying the current state while navigating on the website, retaining the styles and functi ...

Tips for including headers in a GET request with superagent

Here is a basic code snippet: const superagent = require('superagent'); superagent.get('https://api.arabam.com/pp/step') .set('apikey', '_V85Kref7xGZHc1XRpUmOhDDd07zhZTOvUSIbJe_sSNHSDV79EjODA==') .end((err, res) =& ...

What is the proper way to store the output in a variable? Angular and XLSX

I am attempting to read an Excel file from an input using Angular and convert the data into an array of objects. Here is how my components are structured: import * as XLSX from 'xlsx'; import { Injectable } from '@angular/core'; @Injec ...

Have you considered utilizing encodeURIComponent to encode both the key and parameter values?

When I use encodeURIComponent in this code snippet: export function getDownloadFileUrl(fid: string,bgColor: string) { const params = encodeURIComponent("id=" + Number(fid) + "&bgColor=" + bgColor); const config = { m ...

The testString's dependencies are unresolved by Nest

Encountered Problem: Facing the following issue while running a unit test case Nest is unable to resolve the dependencies of the testString (?). Please ensure that the argument SECRET_MANAGER_SERVICE at index [0] is available in the context of SecretMa ...

Sending the HTML input value to a Knockout view

Can someone assist me with a dilemma I'm facing? Within CRM on Demand, I have a view that needs to extract values from CRM input fields to conduct a search against CRM via web service. If duplicate records are found, the view should display them. Be ...

Exploring Typescript and Clean Architecture with an In-Memory Database/Repository

Currently, I am integrating clean architecture in my latest project and facing challenges with repositories, data sources, and terminology. My aim is to test my useCases using an in-memory repository as I am only concerned about the business logic at this ...

Facing issues with query parameters functionality

For my Angular2 application, I need to include some optional parameters in a route. Since they are not mandatory, I have opted to utilize the queryParams feature. This is the code snippet I am using to pass the optional argument: public recoverPassword() ...

A specialized <T> interface, now enhanced with additional functionalities

Looking to create a generic type (with parameter T) that exhibits the following behavior: If K represents a key of T, allow the value type to be either T[K] | ((params?: Partial<T>) => string) If K is not a key of T, allow the value type to be ( ...

Error: Unable to execute function abc, it is not defined as a function in this context

Having trouble with a fronted or JavaScript issue where it can't find the defined function in the file. I'm working on integrating Apple Pay and need to call the back-end API based on a specific event. Here is my code. ACC.payDirect = { _autoload ...