What is causing the consistent occurrences of receiving false in Angular?

findUser(id:number):boolean{  
    var bool :boolean =false
    this.companyService.query().subscribe((result)=>{
           for (let i = 0; i < result.json.length; i++) {
               try {
             if( id == result.json[i].user.id)
                 {
   console.log('id-user:',id ,'user in company:',result.json[i].user.id,'company :',result.json[i].id )
                     bool = true
                   }
                } 
               catch (error) {}
           }
           console.log('final bool value:',bool)
      })
      console.log(bool)
      if(bool) return true;else return false
  }

 confirmDeletion(login) {
    this.userService.find(login).subscribe((response)=>{
         const id =response.id
        console.log('result :', this.findUser(id))
    })
}
  • result : false
  • id-user: 7202
  • user in company: 7202 company : 5151
  • final bool value : true

Why am I always receiving a false as the output?

Answer №1

Due to the asynchronous nature of this.comapanyService.query(), there is a delay in receiving the result. This results in the code below being executed before the actual result is obtained (when the boolean value has not yet been changed):

var bool :boolean =false
console.log(bool)
if(bool) return true;else return false


*Now that we have received an answer*
Continue with other tasks inside the subscribe function

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

Having trouble establishing a connection to the FTP server through the "ftp" package provided by npm

Attempting to establish a connection to a Secured FTP server using the "ftp" package. When connecting to an unsecured server, everything functions as expected with all events firing and content being displayed. However, upon trying to connect to a server ...

What is the correct method to choose an element in jQuery based on the function's id parameter

I'm having trouble deleting an item in my to-do list app. deleteToDoItem: function(id) { $(id).remove(); console.log(id); }, Here is the function that calls deleteToDoItem: function deleteItem(event) { var itemID, splitID, t ...

What is the best way to utilize a variable in jQuery outside of a function?

I am attempting to utilize the .index method to determine the position of the image that is clicked on. I then need to use that number in another variable which must be external to the function. var index; $('.product img').click(function () ...

Tips on organizing a typescript object/StringMap in reverse order to prioritize the last element

I've just started working with TS/React in a .tsx file and I'm trying to add a key/value pair to a StringMap at the very first index. Below is the code snippet that: takes the StringMap 'stats' as input, iterates through each row, re ...

Updating Vue component property when Vuex store state changes: A step-by-step guide

As I work on developing a straightforward presentation tool using Vue js and Vuex to manage the app state, I am facing a challenge in implementing a feature that tracks changes in the presentation such as title modifications or slide additions/removals. Cu ...

What causes axios to return a z_buf_error?

I've encountered an issue with axios returning an error cause: Error: unexpected end of file at BrotliDecoder.zlibOnError [as onerror] (node:zlib:189:17) { errno: -5, code: 'Z_BUF_ERROR' I'm puzzled as to why this functio ...

Building a promotional widget

I'm currently working on developing an ad widget that can be easily reused. I'm debating whether to use jQuery or stick with pure JavaScript for this project. What are your thoughts on the best approach for creating a versatile and efficient ad w ...

Limit the execution speed of a JavaScript function

My JavaScript code is set up to trigger a click event when the user scrolls past a specific element with the class .closemenu. This is meant to open and close a header menu automatically as the user scrolls through the page. The problem I'm facing is ...

Is it possible that overwriting my observable variable will terminate existing subscribers?

I am looking for a way to cache an http call and also trigger the cache refresh. My UserService is structured like this: @Injectable() export class UserService { private currentUser$: Observable<User>; constructor(private http: HttpClient) { } ...

Can JavaScript be used to dynamically assign events to elements on a webpage?

I am currently using the following code: if ( $.support.touch == true ) { $(window).on('orientationchange', function(event){ if ( full == false ) { self.hideAllPanels("7"); } }); } else { $(window).on(&apo ...

Steps to creating a custom text editor using React for generating blog content and storing it in a MongoDB database

I have a challenge of building a rich text editor for my web app, specifically for creating blog posts that will be saved in the database for user viewing. Initially, I planned to use a form with input fields where the title and content of the blog post w ...

Assigning binary messages a structure similar to JSON for the purpose of easy identification

Is there a way to differentiate binary messages from a server by tagging them with a type attribute? Currently, I am working with node.js and sending binary images as blobs to my client. However, I now also need to send other file types like .txt over the ...

Addressing important problems post npm audit

I recently encountered some issues after running the npm audit command on a project that was just updated to angular 15. Upon inspection, the npm audit flagged a critical vulnerability related to hermes-engine with a fix available through the 'npm au ...

The onChange event for React select is being triggered twice, incorrectly using the old value the second time

I am currently implementing React Select to display a list of items. When an item is changed, I need to show a warning based on a specific flag. If the flag is true, a dialog box will be shown and upon confirmation, the change should be allowed. After each ...

Display when moving up and conceal when moving down

Is there a way to make the div appear when scrolling up and down on the page? I'm new to jquery and could use some assistance, please. ...

Building forms within an AngularJS directive

I recently developed an AngularJS directive that includes a form. This form consists of a required text field along with two additional child forms. Each child form also contains a required text field. The distinguishing factor between the two child forms ...

What could be causing the issue with my custom AlloyEditor UI extension?

After following the instructions in this guide to integrate alloyeditor as a WYSIWYG editor into Contentful, I successfully added the extension to my contentful staging space. However, despite copying the html page from the github repository and includin ...

JavaScript method to clear a variable

Can JavaScript prototype be used to add a method to a variable that is undefined? For instance, we can use the following code: var foo = "bar"; String.prototype.doTheFoo = function(){ console.log("foo is better than you"); }; foo.doTheFoo(); This c ...

Choosing the Laravel 6 option for editing via AJAX: A step-by-step guide

I am looking to update a user who resides in a specific state within a country. The country and state fields are dropdown select options, with a relationship established between them and the user. The state field is populated based on the selected country. ...

What causes the delay in CSS animations?

Is there a way to trigger an "updating" image to spin while a long JavaScript function is running? I am currently using JQuery to add a class called "spinning", defined in my CSS for the animation. The problem is that when I add the class and then call a l ...