Tips for refreshing the modified toggle in angular2

I currently have a newsletter subscription that is initially set based on the newsletter I receive when the user logs in.

However, when I toggle the newsletter option, I receive a "successfully updated" message but the newsletter remains set to false even though I changed it to true. Can anyone offer assistance with resolving this issue?

HTML:

<div class="col-lg-4 col-md-4 col-sm-4 col-xs-12 text-center">
        <span style="font-weight: 100;">Newsletter{{company.newsletter|json}}</span>
        <ul class="toggle">
          <li>
            <mat-slide-toggle class="showToggle" name="subscribe" [(ngModel)]="company.newsletter" #slider required (click)="openPopup($event,company)">
            </mat-slide-toggle>
          </li>
        </ul>
      </div>

Ts:

**Checklogin:**
this.ApiService
      .checklogin()
      .subscribe(
        user  => {
          this.company= user.data[0];
        }, error => {
          console.log(error);
        });

**newsletter toggle**
        openPopup(event,company) {
    var userData:any = {
      _id: company._id,
      email: company.email,
      active: company.active,
      newsletter:company.newsletter
    };
      this.ApiService
          .editUserToggle(userData._id,userData)
          .subscribe(
              user => {
                console.log(user);
                this.toasterService.pop('success', 'User subscribed Successfully');
              }, error => {
                if(error.data && error.data.length > 0) {
                  this.toasterService.pop('error', error.data);
                } else {
                  this.toasterService.pop('error', 'Something went wrong!');
            }
         })
  } 

Despite receiving a success message, the newsletter still shows as false.

Answer №1

Receiving a success message from the update api may seem promising, but it's important to note that the value returned will be the same as what you sent, resulting in a false outcome.

To address this issue, consider altering the newsletter value using the following code:

var userData:any = { newsletter: !company.newsletter };

openPopup(event,company) {
    console.log(company);
    if(!this.loggedIn){
        event.preventDefault();
        this.signIn.show();
    }
    var userData:any = { 
        _id: company._id,
        email: company.email,
        active: company.active,
        newsletter: !company.newsletter
    };
    console.log(userData);
    this.ApiService
    .editUserToggle(userData._id,userData)
    .subscribe(
    user => {
        console.log(user);
        this.toasterService.pop('success', 'User subscribed Successfully');
        this.newsletter = userData.newsletter;
        }, error => {
        if(error.data && error.data.length > 0) {
        this.toasterService.pop('error', error.data);
        } else {
        this.toasterService.pop('error', 'Something went wrong!');
        }
    })
}

However, simply changing the code is not enough. To ensure that the model value is updated accordingly, remember to include:

this.newsletter = userData.newsletter;

Answer №2

Make sure to update the newsletter service by toggling the company.newsletter ngModel value when calling the service.

openPopup(event,company) {
var userData:any = {
  _id: company._id,
  email: company.email,
  active: company.active,
  newsletter:company.newsletter
};
  this.ApiService
      .editUserToggle(userData._id,userData)
      .subscribe(
          user => {
            console.log(user);
            this.toasterService.pop('success', 'User subscribed Successfully');
          }, error => {
            if(error.data && error.data.length > 0) {
              this.toasterService.pop('error', error.data);
            } else {
              this.toasterService.pop('error', 'Something went wrong!');
        }
     })

}

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

What is the best way to customize the interval time for my specific situation?

I'm working on setting an interval in my app and I have the following code: HTML <div class="text"> {{currentItem.name}} </div> <ul> <li ng-repeat="item in items" ng-click="pickItem($index)">{{item.type}}</li> ...

The extent of the modal window (AngularJS directive)

I've been experimenting with a modal window feature using Angular UI Bootstrap. Within the parent controller, I've defined the following function: $scope.open = function () { var modalInstance = $modal.open({ templateUr ...

Verify the data types of components received as props in a Typescript React application

I have a question regarding type checking in React components passed as props: What is the method for ensuring that only allowed components are passed as props? Allow me to demonstrate. We have the component we wish to pass around: type CustomProps = { ...

Where can I locate the Socket.IO server within the local area network (LAN)?

I am currently in the process of developing an application that facilitates connections between devices within the same network. In my design, any device can act as a server, and I aim for clients to automatically detect the server without requiring users ...

Retrieve information using AJAX via POST method

I find myself in a bit of a pickle at the moment. I've been researching for hours, and I still can't seem to figure out this seemingly basic issue. It would be greatly appreciated if someone could offer me some quick advice. So here's my dil ...

What is the best way to reposition a column as a row when the user interface transitions to a different screen or

Welcome to my UI experience! https://i.stack.imgur.com/gOwAn.png Check out how the UI adapts when I resize the browser: https://i.stack.imgur.com/MyxpR.png I aim for the left component to be visible first, followed by scrolling to see the right compone ...

javascript update HTML content

Hello, I am trying to call a function called changeDivHTML which passes an image. <a href="javascript:void(0)" onclick="changeDivHTML(<img src='.DIR_WS_IMAGES .$addimages_images[$item]['popimage'].'>)"> This function ad ...

Having trouble with React's useEffect and React-Query's useQuery?

As a React newbie, I'm trying to implement global error handling using a context provider and a custom hook. Main Objective: Implementing a system to handle errors at the global level. The Issue: Errors reappear immediately after being removed. I s ...

What is the process for defining functions with distinct data types while allowing variables to have multiple data types?

I am facing a declaration issue - or rather, a challenge in comprehending Typescript. Let me illustrate the scenario: public migrationSource: Skater | Rink; public migrationDestination: Skater | Rink; public migrationMode: MigrationMode; ngOnInit() { ...

NextJS API routes consistently provide a status code of 200 upon execution

I am new to the concepts of Next.js, and I recently encountered an issue while attempting to fetch data from an API. The API is designed to check if a user session exists (i.e., if the user is logged in) and then returns a JSON response through a GET reque ...

I am unable to store rich text fields using LocalStorage

My goal is to store form data in localStorage, but I'm facing an issue with rich text fields not saving their data. Regular HTML fields like textboxes work fine. In my Razor markup for the field (using MVC), here is an example: <div class="form-g ...

"ExceptionThrownByMoveTargetOutOfBounds in Selenium WebDriver for IE9 and Firefox

Having trouble with the FireFox/IE9 driver in Selenium? When using the Actions class and its moveToElement method, I keep encountering a MoveTargetOutOfBoundsException error. Despite trying different solutions like Coordinates, Point, and javascriptexecuto ...

Implementing Firebase as an Authentication Middle Layer for Express.js

I am currently working on developing an authentication middleware to verify the presence of a valid firebase token in the request header. Here's the code snippet: auth.ts import * as firebase from 'firebase-admin'; import { NextFunction, Re ...

Which specific technological platform or framework would be most suitable for constructing a similar project?

https://i.stack.imgur.com/LL1g9.png Looking at the image provided, my goal is to allow users to navigate between pages on the Home page without having to refresh the entire browser window. I believe this can be achieved using Ajax technology, am I correct ...

Endless loop in React Native with an array of objects using the useEffect hook

For the current project I am working on, I am facing the challenge of retrieving selected items from a Flatlist and passing them to the parent component. To tackle this issue, I have initialized a local state as follows: const [myState, setMyState] = useS ...

What are the consequences of altering meta tags once the DOM has fully loaded?

While delving into the A-Frame source code, I noticed that the library uses JavaScript to set various meta tags. It seems safe in the context of A-Frame as Mozilla recommends importing their library as a blocking, synchronously loaded script in the <he ...

Define the data type for the toObject function's return value

Is it possible to define the return type of the toObject method in Mongoose? When working with generics, you can set properties of a Document object returned from a Mongoose query. However, accessing getters and setters on these objects triggers various v ...

How can I access a DOM element in an AngularJS 2 TypeScript file?

As a newcomer to AngularJS, I am attempting to add a spinner as a background to all images on my website. Since there are multiple images, using a single variable like isLoaded in the TypeScript file is not feasible. Here is how I am implementing it in th ...

Tips for Effectively Declaring a Variable with React's useState

How should I correctly specify variable types in useState? In the code below, the value for alert must be either "success","warning", "error", or "info" const [alertValue, setAlertValue] = useState("error" ...

The importance of handling undefined values in TypeScript and React

There is a condition under which the IconButton element is displayed: {value.content && <IconButton aria-label="copy" onClick={() => copyContent(value.content)}> <ContentCopy /> </IconButton> } However, a ...