Looking to send a POST request with a particular object type

Currently, I am working with an abstract class called "Achievement" which has two subclasses: "ExhibitsVisitedAchievement" and "RouteFinishedAchievement". My goal is to create instances of these achievements by using a POST call to the relevant API endpoint, either for an ExhibitsVisitedAchievement object or a RouteFinishedAchievement object.

The APIs available to me are as follows: 1. GET /api/Achievements/types - to retrieve the types of achievements 2. POST /api/Achievements/ExhibitsVisited - for recording visited exhibits 3. POST /api/Achievements/RouteFinished - for marking a finished route

I am currently facing difficulties in implementing the creation method, as I am unsure of how to make a POST request with the correct object to the respective API.

If anyone could provide guidance on this matter, it would be greatly appreciated.

As a newcomer to Angular 2, I am doing my best to learn and understand the process.

Thank you.

Answer №1

When creating a service, it needs to follow a specific structure similar to the one shown below:

import { Http, Response } from '@angular/http';

@Injectable()
export class AchievementService {

    constructor(private http: Http) { }

addVisitedAchievement(exhibitsVisitedAchievement: ExhibitsVisitedAchievement): Observable<ExhibitsVisitedAchievement> {
        const copy = this.convert(exhibitsVisitedAchievement);
        return this.http.post('/api/Achievements/ExhibitsVisited', copy)
        .map((res: Response) => {
            return res.json();
        });
    }

addFinishedRoute(routeFinishedAchievement: RouteFinishedAchievement): Observable<RouteFinishedAchievement> {
        const copy = this.convert(routeFinishedAchievement);
        return this.http.post('/api/Achievements/RouteFinished', copy)
        .map((res: Response) => {
            return res.json();
        });
    }
private convert(exhibitsVisitedAchievement: ExhibitsVisitedAchievement): ExhibitsVisitedAchievement {
    const copy: ExhibitsVisitedAchievement = Object.assign({}, exhibitsVisitedAchievement);
    return copy;
}

}

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

When selecting a MenuItem, only a ReactOwner has the ability to add a ref using addComponentAsRefTo(...)

I'm currently working on a basic component that looks like this: class App extends React.Component<{}, {}> { constructor() { super(); } render() { return ( <MuiThemeProvider muiTheme={muiTheme}> <div> ...

What is the best way to append something to the textContent property of an HTML tag within a markup page?

While working on resolving an XSS vulnerability in the jqxGrid where the cell content is rendered as HTML, I encountered a scenario like this: <a href="javascript:alert('test');">Hello</a>. To address this issue, I am exploring ways t ...

Improving the App() function in React and Typescipt

When working on my React/Typescript app, I encountered a challenge with the length of the code in one of the sections. Despite watching tutorials and searching for solutions, I couldn't find a clear way to refactor it. The specific issue is with refa ...

Executing multiple instances of the cascading dropdown fill method in Angular 7

I am currently working on an Angular app that includes cascading comboboxes for country and state selection. However, I have noticed that the get states() method in my state.component.ts file is taking a long time to run. What could be causing this issue? ...

Enhance your website with unique and custom fonts using

I am utilizing this repository. How can I incorporate custom fonts into my project? I have created a folder named "fonts" within the assets directory and placed my fonts there. fonts.scss @font-face { font-family: 'Lato'; src: url('../ ...

Issues with Cloud9 Angular and NodeJS connecting to API on a separate port of the same server

I am currently utilizing an AWS Cloud9 IDE for my project. Angular is running on port 8080, while my NodeJS (with Express) server is running on port 8081. In my Node app.js file, I have set up CORS headers as follows: const app = express(); app.use(expre ...

What is the best way to extract a nested array of objects and merge them into the main array?

I've been working on a feature that involves grouping and ungrouping items. A few days ago, I posted this question: How can I group specific items within an object in the same array and delete them from the core array? where some helpful individuals ...

What is the process for accessing getBoundingClientRect within the Vue Composition API?

While I understand that in Vue we can access template refs to use getBoundingClientRect() with the options API like this: const rect = this.$refs.image.$el.getBoundingClientRect(); I am now attempting to achieve the same using template refs within the com ...

Inversify is a proven method for effectively injecting dependencies into a multitude of domain classes

Struggling to navigate dependencies and injections in a TypeScript-built rest web service without relying heavily on inversify for my domain classes, in line with the dependency inversion principle. Here's an overview of the project structure: core/ ...

What causes the discrepancies in versions of dependencies listed in the package-lock.json file?

Currently, I am developing an application using angular 10. I have noticed that the version of a dependency in my package-lock.json file is different from what I specified in my package.json after running the command: npm install. For example: In my pack ...

What are the steps to integrate a database into my Next.js application?

While I was experimenting with integrating postgresql into a nextjs project, I encountered an error 405 when trying to create an account. Below is the error message in the browser console: page.tsx:14 POST http://localhost:3000/api/auth/ ...

Error TS2339: The type 'never' does not have the property 'getBoundingClientRect'

While optional chaining should suffice, I may have gone a bit overboard in attempting to satisfy TypeScript: const ref = useRef() if (ref !== undefined) { if(ref.hasOwnProperty('current')) { if (ref.current !== undefined ...

Content from PHP's unlink() function continues to persistently display

I run an Angular front end along with a PHP back end for my website. I utilize PHP's unlink function to remove specific images from Angular's assets folder: $fileToDelete = "../src/assets/images/".$name; unlink($fileToDelete) or die("Error delet ...

Running cypress tests with regression or smoke tags within nx workspace is a straightforward process

I have a cypress project set up and I am trying to run cypress tests based on tags using the nx command. cypress grep--->"@cypress/grep": "^4.0.1" After applying the nx command like this: nx run e2e:e2e --tags=@regression The issu ...

Dealing with a situation where different functions need to be called based on a condition while using unique button names. This is

<button type="button" class="btn btn-primary ms-4" (click)="update()">Save</button> <button type="button" class="btn btn-primary ms-4" (click)="create()">Add</button> B ...

When attempting to utilize the Angular2 http.get function to retrieve data from a Restful Webservice, I encountered an issue where the error status 200 was returned

Angular 2 Issue with http.get Request to Restful Webservice When I try jsontest.com, I receive the value properly. getCurrentTime() { //return this.http.get('http://date.jsontest.com') return this.http.get('http://localhost:80 ...

Auth0 with auth0-lock will only authenticate when utilizing a debugger to carefully navigate through the code

As stated in the title, I am attempting to integrate auth0-lock with an Angular 2 SPA and an ASP.NET Core API. However, I am encountering difficulties with authentication during testing. My application is packed using webpack, and all unnecessary reference ...

Convert JSON data into an array of strings that are related to each other

I'm encountering an issue with converting JSON into a string array I must convert a JSON into a string array to dynamically INSERT it into our database, as I need this to work for any type of JSON without prior knowledge of its structure. Here is th ...

Tips for adjusting card content to fit its size in material ui?

I'm looking to implement Material UI cards in a grid layout, each containing a Highcharts chart as shown in this demo. However, I'm facing an issue where the content does not adjust properly when the card size is fixed. How can I resolve this? A ...

Errors from NestJS microservice class validator are visible in the docker container but do not appear in the API response

Seeking assistance with displaying validation errors in my NestJS project using class validator. This is my first time working with microservices and NestJS, as it's for a school project. Errors from my 'user' microservice container are not ...