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 functionality does the --use-npm flag serve in the create-next-app command?

When starting a new NextJS project using the CLI, there's an option to use --use-npm when running the command npx create-next-app. If you run the command without any arguments (in interactive mode), this choice isn't provided. In the documentati ...

Ways to adjust the size of div and its elements to fit the window dimensions

When resizing the window, the banner image shrinks while the header and header items remain the same size. However, there is an issue when the header takes up around 30% of the screen in phone view. Here is the CSS code I am using: .headerdiv{ width: ...

What are some methods for bypassing the use of a keypad for a specific input

I have a mobile app built with Ionic. When the user taps on any input field, the keypad opens which works well. However, I have a datepicker with an input field where I want to prevent the keypad from opening. How can I achieve this? <div class="col" ...

The Angular form remains invalid despite all form fields being valid

After spending hours on an Angular form validation project, I have encountered an issue that has been difficult to resolve. The form I created seems to be working fine based on a demo I shared, where it shows the form status as VALID. However, when running ...

Tips for adjusting CSS font sizes within a contenteditable element?

I am looking to develop a compact HTML editor using JavaScript that allows me to customize the font-size of selected text with a specific CSS value. The documentation states that the FontSize command is used like this: document.execCommand("FontSize", fal ...

When attempting to access API>19 on my Android device, I encountered an error in my Interface to Java that stated: "TypeError: Android.method is not a function."

Having my minimum API set to 16, everything seems to be working fine. However, debugging has become quite a challenge. I've read that after API 19, the Chrome debugger can be used. But when it comes to interfacing with Java code, I encounter the error ...

An error occurred while trying to access the object null in React-Native, specifically when evaluating 'this.state.token'

I encountered an error while trying to execute a class in a view: When running the class, I received the following error message: null is not an object (evaluating 'this.state.token') The problematic class that I'm attempting to render: c ...

In what ways can one determine the function parameter of a union type?

I am working with a union type of functions: function Function1(arg0: string, arg1: any[], name: "hello" | "bye") { return name; } function Function2(arg0: string, arg1: any[], name: "foo" | "bar") { return name ...

Dealing with Javascript exceptions and sending email notifications in Django

I appreciate the traditional method of handling server-side exceptions in Django using Python. I am interested in finding a similar approach for client-side exception handling in JavaScript. So far, I have come across only one option which is DamnIT, but ...

Guide on how to use JavaScript to make an HTML5 input field mandatory

I am facing an issue with setting input fields as required based on radio button selection in a form. Initially, all fields should have required=false, but I'm unable to achieve this. No matter what value I assign to the required attribute, it always ...

Develop a payment confirmation session using Stripe and Node.js

I have set up a POST request using Stripe to handle customer payments let paymentData = { errorMsg:'', key: process.env.STRIPE_PUBLIC_KEY } const session = await stripe.checkout.sessions.create({ payment_method_types: ...

Automatic button rotation

I managed to set up a button that works on click with a delay, making it semi-automatic. However, I'm struggling with getting it to not pause after just one click. Here's what I have so far: <!DOCTYPE html> <html> <body> &l ...

Minimum number of coins required for a specific amount

I need assistance creating a JavaScript/jQuery function to determine the minimum number of coins required to reach a specified total amount. Here is an array object containing different coin values: var coins = [ { pennies: 200, prin ...

Struggling to retrieve the tagName attribute when clicking in JavaScript

I am trying to extract the tagName of any element within an iframe when it is clicked. Unfortunately, my JavaScript code is not working as expected. As a beginner in JavaScript, I would appreciate some guidance on where I might be going wrong. <div cl ...

Issue with ESlint global installation in macOS root terminal

Having trouble installing ESlint globally on my Mac running Mojave 10.14.6. Every time I try to run 'npm install -g eslint' I keep encountering this error: Your operating system has rejected the operation. npm ERR! It seems that you lack the nec ...

How can data be transferred from a parent component to a child component using MaterialUI's styling functionality?

Recently delving into the world of reactjs, I've been tinkering with a basic page that incorporates authentication using state. To spruce up the design, I decided to use the MaterialUI framework. The issue I'm facing is related to sending the lo ...

Using npm webpack-mix to execute a JavaScript function stored in a separate file

Currently, I am facing a challenge with accessing a function that is defined in the table.js file from within my index.html. Here is a snippet of the code: table.js let table; function set_table(table) { this.table = table; consol ...

What is the method for configuring my bot to forward all logs to a specific channel?

const logsChannel = message.guild.channels.cache.find(channel => channel.name === 'logs'); I am looking to set up my bot to send log messages for various events, like member join/leave or message deletion, specifically in a channel named &apo ...

Is there a way to integrate the javascript and jQuery functions in order to conceal a button?

I recently acquired the File Upload script known as Simple Photo Manager and I am looking to incorporate jQuery functions with the existing JS code in the script. My main goal is to make the Delete button disappear once it has been clicked. However, I am ...

Navigating on Blogger can be a tricky task when it comes to searching and

I recently added a Table to my blogger post, along with an input form for readers to easily search data. After finding the code on W3Schools (link here), I implemented it successfully. However, I am looking to make some improvements. Here is my question: ...