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

FoxyWeb Requests: Utilizing XMLHttpRequest in Firefox Extensions

While I've come across plenty of examples on how to create xhr requests from Firefox Add-ons, I'm currently exploring the new WebExtensions framework (where require and Components are undefined) and facing an issue with sending a simple XmlHttpRe ...

Calculating variables in JavaScript

Explanation from Mozilla Documentation: console.log((function(...args) {}).length); // The result is 0 because the rest parameter is not counted console.log((function(a, b = 1, c) {}).length); // The result is 1 because only parameters before th ...

What is the best way to modify a variable in a nested element using ng-click in the parent element?

Review this code snippet: <section class="page-section about-us" scroll-bookmark="about-us" ng-click="activeSection=true" ng-init="activeSection=false"> <div class="page-content sub-content active-section">{{activeSection}} < ...

When using translate.get with an array of strings in Angular 5, the function will return both the keys and values, not just

Currently, I am utilizing Angular 5 to manage internationalization through ngx-translate within my code. To elaborate on the issue at hand, I have a data table that pulls information from a web service and displays it correctly. There is also a button tha ...

What steps can I take to address this issue with my express node and ejs?

Hey there, I'm new to node.js and I've been encountering this error message. Can someone please provide some insight? Error: Could not find matching close tag for "<%=". at /Users//Desktop/Web Development/getting_started_express js/node_m ...

The component <FormControl /> does not support the variant prop

It's perplexing to me why <FormControl /> doesn't seem to accept the prop variant. Even though the documentation suggests that this prop is available. import React from "react"; import { render } from "react-dom"; import FormControl from " ...

Issue encountered while configuring server using express.js

Here is the server.js file I am working on, but I encounter a specific error when trying to set up the server with Express.js var express = require('express'); var app = express(); var PORT = process.env.PORT || 3000; app.all('/*', ...

Exploring the functionality of the $.each jQuery iterator. Can someone clarify the distinctions between these two methods?

Having vertices as an array of google.maps.LatLng objects means that they should return latlng points. The first code snippet works perfectly fine, however, I encounter issues when using the second one. // Iterate over the vertices. for (var index =0; ind ...

Issues arising from using async/await in conjunction with .then() in vue.js login function, causing fetch process not to wait for completion

I implemented a login function to verify credentials on my backend server, but I am facing an issue with waiting for the server response. Despite following the es7-async-await.js guide and trying various async/await and promise techniques, the function sti ...

Concentrating on div elements using React

Can the focus() method be used to focus on a div element or any other elements? I have added a tabIndex attribute to a div element: <div ref="dropdown" tabIndex="1"></div> When I click on it, I can see that it gets focused. However, I am att ...

Tips for including MUI icon within a list displayed on a map:

Initially, I brought in the AccountCircle Icon from MUI: import { AccountCircle } from '@mui/icons-material'; Then, I utilized styled to customize the icon: const UserIcon = styled(AccountCircle)({ margin: '0px 0px 0px 0px', }); My ex ...

Creating interactive labels in a histogram that update based on the user's input

Currently, I have operational code in place that takes input data and generates a histogram based on set thresholds. When the code is executed, the histogram changes dynamically as the threshold slider is adjusted. However, there seems to be an issue wit ...

Upgrading to Angular 14 has caused issues with component testing that involves injecting MAT_DIALOG_DATA

After upgrading Angular from 14.1.1 to 14.2.10 and Material from 14.1.1 to 14.2.7, a peculiar issue arose when running tests with the default Karma runner. I am at a loss as to what could have caused this problem, so any advice would be appreciated. The u ...

The back-to-top button guides users back to their last visited page

I'm excited to explore AngularJS and I want to add two "return to top" buttons on different pages. Here's what I have so far: Page 1: <h1 id = "top"> .......... <a href="#top" target = "_self">Return to Top</a> Page ...

Can anyone explain how to conduct a live search using Ajax?

Hello, I'm currently working on a project where I've successfully connected a large database to a website and implemented an AJAX live search feature. However, I am now in need of a non-live version of the AJAX search. The current setup displays ...

Slim 4 with Angular 10: Issues with downloading PDF files through API, as Angular blob response is coming back empty

Struggling to integrate the download PDF Angular API with Slim 4 API. The response from Slim can be seen in the browser network, but when trying to parse it in Angular, it comes back empty. All the necessary headers have been added on both Angular and Slim ...

Can I use a custom font in an HTML5 canvas?

Has anyone had success importing a custom font for use in HTML5 canvas? I've been trying to do this by loading the font file on my computer, but all my attempts have failed so far. The canvas keeps showing the default font instead of the one I want to ...

Why is it that when I refresh the page in Angular, my logged-in user is not being recognized? What could be causing this

I am developing a Single Page Application using the combination of Angular JS and Node JS. In my HTML file, I have defined two divs and based on certain conditions, I want to display one of them using ng-if. However, I noticed that the model value used in ...

Guide to using vite-plugin-rewrite-all in conjunction with Quasar for Vue 3 - or alternative method to enable periods in paths

Encountering a 404 error when using quasar+vite in vueRouterMode: 'history' mode with paths containing a period/dot in the id? This issue has been discussed in various places: https://github.com/vitejs/vite/issues/2415 https://github.com/vitejs/ ...

Error encountered in ngtsc(2345) where an argument of type 'Event' is being used instead of an expected parameter type of 'SortEvent'

I recently started using angular and encountered an issue while trying to sort columns. The error message I received was: Argument of type 'Event' is not assignable to parameter of type 'SortEvent'. Type 'Event' is missing t ...