Submitting information to a server

I have a simple Angular 6 app with follow and unfollow buttons. When you click follow, the number increases. I want to save these follower numbers to a JSON server.

Here is the link to the JSON server documentation: JSON Server Documentation

To see a demo of what I'm trying to do, click here: demo. Here is my JSON file:

  "data": [
    {
      "id": 1,
      "following": 121,
      "followers": 723,
    } 
  ],

Below is the HTML code:

<div class="container">
  <div class="row">
    <p class="col">{{numberOffollowers}}</p>
    <button class="col btn btn-success" (click)="followButtonClick()">Follow</button>
    <button class="col btn btn-danger" (click)="unfollowButtonClick()">Unfollow</button>
  </div>
</div>

Here is the service:

import { Injectable } from '@angular/core';
import { Statuses} from '../model/statuses';
import { HttpClient } from '@angular/common/http';

@Injectable()
export class UsersService {

  status: Statuses[];
  constructor(private http: HttpClient) { }
  statusUrl = 'http://localhost:3000/statuses';

  getStatuses() {
    return this.http.get<Statuses[]>(this.statusUrl);
  }
  addStatus(status: Statuses) {
   return this.http.patch(this.statusUrl, status);
  }
}

Here is the TypeScript file:

import { Component, Input } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { UsersService } from './service/users.service';
import { Statuses} from './model/statuses';
@Component({
  selector: 'like-box',
  templateUrl: 'like.component.html',
  styleUrls: [ './like.component.css' ]
})
export class LikeComponent  {
 numberOffollowers : number = 69;
  status: Statuses[];

  constructor(private http: HttpClient, private usersService: UsersService) { }

  followButtonClick() {
    this.numberOffollowers++;
  }

  unfollowButtonClick() {
    this.numberOffollowers--;
  }

   addStatus() {
    this.usersService.addStatus(this.numberOffollowers)
    .subscribe(data => {
      this.status.push(this.numberOffollowers);
    });
  }
}

Check out my app by visiting this link: app.

The current setup is not working. What adjustments are needed in my app to successfully save those followers' numbers to the JSON server?

Answer №1

A new feature was implemented in the like component called addStatus(). However, I have not observed any instances where this function is being invoked. It is crucial to include a status button and subsequently call the addStatus() function.

Answer №2

Make sure to call the addStatus method when handling button clicks in your Angular component, rather than just updating the numberOfFollowers count.

import { Component, Input } from '@angular/core';
import { UsersService } from './service/users.service';
import { Statuses} from './model/statuses';
@Component({
  selector: 'like-box',
  templateUrl: 'like.component.html',
  styleUrls: [ './like.component.css' ]
})
export class LikeComponent  {
 numberOffollowers : number = 69;
  status: Statuses[];

  constructor( private usersService: UsersService) { }

  followButtonClick() {
    this.numberOffollowers++;
    this.addStatus()
  }

  unfollowButtonClick() {
    this.numberOffollowers--;
     this.addStatus()
  }

   addStatus() {
    this.usersService.addStatus(this.numberOffollowers)
    .subscribe(data => {
      this.status.push(this.numberOffollowers);
    });
  }
}

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

I have successfully managed to populate the Google Apps Script listbox based on the previous listbox selection for two options, but unfortunately, I am encountering issues

Struggling to set up 3 list boxes that populate based on each other? At the moment, I have one list box fetching data from a spreadsheet. Could someone assist me in configuring it so that the second list box populates based on the first, and a third list b ...

Dealing with callback errors: error handling is anticipated

In my Vue web application, I have enabled ESLint and encountered an issue with the following code: myApi.get('products/12').then((prodResponse) => { state.commit('ADD_PRODUCT', {product: prodResponse.data}) }, error => { cons ...

Iterating over an array and displaying elements on the webpage

Struggling to access an array and loop through it, but only able to print out one element instead of all. Need a hint on how to solve this issue. See my code below: let toppingsCount; const burger = document.createElement('div'); const toppingsD ...

How can a button be linked directly to a particular list item?

I currently have a HTML tag within my React application that looks something like this: <ul> <li> Item 1 <button> Delete </button> </li> <li> Item 2 <button> ...

What is the best way to transform React API data into props that can be utilized in different components?

I've been struggling with this issue for quite some time now, unable to understand how to manipulate the data in a way that allows me to use it in other components. Although I can display the data correctly, I'm advised to structure it within a f ...

When I try to execute a mutation with Apollo and React, I encounter a 400 error. It could be due to a

Every time I try to perform a mutation, I keep getting a 400 error code for some strange reason. Here is my httpLink code snippet: // ApolloProvider.js const httpLink = createHttpLink({ uri: 'http://localhost:3000/graphql', }); const client ...

What is the internal mechanism used by Angular for routing implementation?

My traditional belief about web browsers has been challenged by the behavior of Angular. I used to think that when a user enters a new URL, the browser would fetch a whole new page from the network and display it, replacing the old one. But with Angular, ...

Error: The value for 'prepareStyles' property is undefined and cannot be read

Can anyone provide some guidance on this code snippet? I am struggling to understand the error message I am receiving. import React, {PropTypes} from 'react'; import TransactionListRow from './TransactionListRow'; import {Table, TableB ...

How to access a controller function within a recursive directive template in Angular version 1.3?

In my parent directive, I am able to access controller functions using the $parent operator. However, this method does not work in recursive child directives. Here is a shortened example of the issue: // Sample controller code (using controllerAs):--- va ...

Change the left position of the sliding menu in real-time

I am currently designing a website with a sliding menu feature. By default, the menu is set to -370px on the left, displaying only the "MENU" text initially. When a user hovers over the menu, it expands to the right, allowing them to select different menu ...

"Initiate an Ajax call in Full Calendar before an event is displayed on the calendar

I need guidance on how to integrate ajax calls with the Full Calendar documentation. Specifically, I want to make an ajax call to a WordPress database before each event is rendered on the calendar. The response from the call will determine the color of the ...

How can child components in ReactJS be conditionally rendered based on the status of userData loading?

It seems like there might be an issue with how we handle user login in our application. Whenever a user logs in, the redux state is updated with the server response. Many components rely on this logged-in status. We pass the currentUser object down to all ...

Using custom hooks in JSX triggers a TypeScript error when the returned component is accessed

i just created a custom hook // useDropdown.ts function useDropdown(defaultState: number, options: number[]) { const [state, setState] = useState(defaultState); function Dropdown({ name }: { name: string }) { return ( <> <sel ...

Build desktop-style applications using a unique user interface library and integrated development environment designed specifically for HTML, JavaScript

I am looking to create a desktop application using HTML, JavaScript, and AJAX for the purpose of making it available on multiple platforms. I was wondering if there is a UI library and web IDE similar to WebOS Enyo that I can use to build my HTML/AJAX app? ...

Could you provide instructions on how to change mjs files into js format?

Is there a method to change .mjs files to .js files? Some hosting services do not yet support mjs files, so I am interested in converting them to js files. Context: Mozilla's PDFjs has incorporated JavaScript modules (mjs) into their code, but since ...

JavaScript loop used to create markers on Google Maps

I am currently in the process of developing a basic Google map which includes markers and involves looping through the data source for the markers. When I replace key.lng or key.lat with hardcoded values in the code below, everything functions correctly. ...

Angular 4 allows the addition of an image from right to left upon clicking

I've been working on angular 4 and I've successfully implemented the functionality of adding flags. However, the issue is that the flags are currently appearing from left to right. What I'm aiming for is to have the images appear from right ...

How does a web crawler determine which elements to click on when navigating a webpage?

Recently, I developed a crawler application that is able to access a given webpage and extract the HTTP Requests before storing them in an excel sheet. Currently, I have implemented click events for some buttons using jQuery. Now, I am faced with the chal ...

My mongoose sort function doesn't seem to be functioning properly. What could be the issue?

Hey there! I've got a simple API up and running on Node.js, using MongoDB as my database with Mongoose for querying. The issue I'm facing is related to sorting data using the mongoose 'sort' method. Instead of behaving as expected, it s ...

Reorganize mat-table rows using Angular Material's drag-and-drop feature

One of the new features that came with Angular 7 is the powerful DragDropModule: https://material.angular.io/cdk/drag-drop/examples The documentation covers rearranging items in lists and transferring them between different lists, but it doesn't ment ...