Unable to assign values using Promises in an Angular component

While working on a Component HTML file, I encountered an issue with exposing a variable. The variable was supposed to retrieve a value from the response using cl.getMonitors. Strangely, despite seeing console.dir(res) in the console, the value of the variable Site.name remained as 'Agenda'. Can someone provide assistance with this?

import { Component, OnInit } from '@angular/core';
import * as Client from 'uptime-robot';

const apiKey = 'asdasdasdasdasdasd';

const cl = new Client(apiKey);

var Site = { 
  name: 'Agenda',
  status: ''
};

@Component({
  selector: 'app-post',
  templateUrl: './post.component.html',
  styleUrls: ['./post.component.css']
})

export class PostComponent implements OnInit {

  siteStatus: string; 
  siteName: string;

  constructor() { 

  }

  ngOnInit() {

    cl.getMonitors({customUptimeRatio: [1, 7, 30]}, function (err, res) {
      if (err) throw err;
      console.dir(res);

      this.siteName = res[0].friendlyname;
      this.siteStatus = res[0].status;
    });
    
    this.siteName = Site.name;
    this.siteStatus = Site.status;

  }

}

Answer №1

There seems to be multiple questionable code snippets present. It is important to identify the potential cause of the issue -

  1. Is the sequence of request and response correct?

Take a look at the following line. The first argument is err and the second is res. Typically, these are reversed so it's crucial to verify if the sequence is accurate.

  cl.getMonitors({customUptimeRatio: [1, 7, 30]}, function (err, res) {
  1. Verify the response format

Are you accessing the first index element from the response? Is this correct or should it be different? Please share your json for confirmation

  this.siteName = res.friendlyname;
  this.siteStatus = res.status;

3 Ensure that the context of this in getMonitors is correct.

You are using this to retrieve siteStatus and siteName, but there is a possibility that the context has changed and may be pointing to the wrong object.

To resolve this, you can utilize the following syntax:

   cl.getMonitors({customUptimeRatio: [1, 7, 30]}, (err, res) => {
      if (err) throw err;
      console.log("this ", this);
      this.siteName = res[0].friendlyname;
      this.siteStatus = res[0].status;
    });

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 arrange a list of dates without taking into account the year associated with each date?

Currently in my Angular 4 project, I have a list of upcoming birthdays displayed in ascending order, but it is also taking the year into account. What I really need is to sort this list only by the date and month, excluding the year. Could someone please ...

The speed of the jQuery mouse scroll script remains constant and cannot be altered

I've been searching online... I attempted to adjust the scrolling settings on my website but nothing seems to be working. Does anyone have a guide or list of mouse scroll jQuery scripts and functions? (I've cleared caches, performed cross-brow ...

Issues encountered while retrieving API payload in Reactjs using Typescript

Having some trouble storing an API payload in state, as I keep receiving the following error message: Error: Objects are not valid as a React child (found: object with keys {page, results, total_pages, total_results}). If you meant to render a collection ...

Issue with Angular 8: click event is not triggering when using ngFor directive to iterate through arrays of objects

Update: The original post has been modified to omit implementation details and complexity. I am facing an issue with an ngFor loop that invokes a method on a service. The method returns an array which is then iterated over by the for loop. The click even ...

Begin anew with Flip.js

Currently, I am incorporating the jquery flip plugin from nnattawat.github.io/flip to establish a card flipping mechanism on my website. I have successfully implemented the method outlined in the documentation to unregister the flip event from the elemen ...

Tips for uploading files in filepicker with protractor

https://i.sstatic.net/noq46.png Here's a snippet of HTML code you might find useful: <input type="file" class="fileUploadInput" name="fileUpload" id="fileUploadInput" accept="application/msword,application/pdf,text/plain,application/rtf,applicat ...

Issue with populating labels in c3.js chart when loading dynamic JSON data

Received data from the database can vary in quantity, ranging from 3 to 5 items. Initially, a multi-dimensional array was used to load the data. However, when the number of items changes, such as dropping to 4, 3, 2, or even 1, the bars do not populate acc ...

Using jQuery to pass dynamic values to a plugin function

I'm currently utilizing the JSONTable plugin and attempting to dynamically pass values to the 'head' and 'json' parameters by extracting them from an array object. For instance, I aim to load a new json file, convert it to a JavaSc ...

When attempting to use the $http get command, an error may occur due

Is there a way to capture these errors in an Ionic application? ionic.bundle.js:25000 GET net::ERR_CONNECTION_REFUSED Using the following code snippet: $http.get('http://' + ip + '/?custom=1&cmd=' + cmd); I have attempted var ...

Utilize a JSON file to generate a network visualization using the vis.js library

I am currently working with vis.js to generate a visualization. In the example code, I am using the file saveAndLoad.html. The save function works well as it allows me to export a json file. However, I am encountering an issue when trying to load the jso ...

I'm struggling to update a value in my view with Angularjs and Socket.io. It seems impossible to

In order to master AngularJS and NodeJS, I am embarking on creating a chatroom project. Everything seems to be functioning smoothly with Angular controllers and sending data to my NodeJS server using socket.io. However, I have encountered a problem: When m ...

Is it possible to sort an array by both date and time simultaneously?

As I work on developing a schedule app, it is necessary to sort items by both date and time simultaneously. In the current setup, the filtering only considers hours and minutes which is functional, but there is a need to also include dates in the sorting p ...

Angular: The 'Object' type can only be assigned to a limited number of other types

My code works perfectly in Angular 5, but when I try to update it to Angular 8, I encounter an issue: this.awsService.getProfiles().subscribe(profiles => { this.profiles = profiles; if (this.profiles.length > 0 && this.profiles.indexOf(this ...

a guide on accessing key value elements within an array using Ionic 3

Just diving into the world of Ionic, I am currently working on a task to showcase products on the cart page that have been added to the cart. Upon fetching data from a REST API, I can see the response below in the console. "items": { "29.2.2.0.YTowOnt ...

What exactly is the significance of placing a term "in" within a method's parameter list in documentation?

Forgive me for what may seem like a silly question, but I prefer to clarify doubts rather than leave gaps in my knowledge. Let's look at this snippet taken from developer.mozilla.org: void initCustomEvent( in DOMString type, in boolean canBu ...

How can JavaScript Regular Expressions be used for Form Validation?

For my registration form, I am including fields such as userid, name, email, password, confirm password, and affiliation. Using regular expressions in JavaScript, I am validating these fields. I am attempting to display any validation errors within the for ...

What is the method for accessing a marker from beyond the map on OpenStreetMap?

Recently, I made the switch from using Google Maps to OpenStreetMap in my project due to the request limit constraints imposed by Google. My client needed a higher request limit, but was unable to afford the costs associated with increasing it on Google Ma ...

Issue with next.handle not functioning properly in Angular 8 when re-requesting

In the code snippet below, the issue is that even after the token expires (401), the API for fetching the refresh token is called, but the request is not re-sent with the updated token using the inner next.handle(). export class InterceptService implements ...

Setting a default currency value (either in dollars or euros) in an input field

Is there a way to automatically insert a currency symbol (€, $) in a text field by default when entering a number? Are there any default values for this feature? Thank you Here is an example ...

Is the presence of an excessive number of arguments in the object that includes functions an instance

In my program, I have implemented a feature where the user can provide an array to determine which functions are executed in a loop. However, managing the list of variables that need to be passed into each function has become challenging as the list keeps ...