Tips on extracting the value from an observable and storing it in a variable

I am facing a challenge in returning a value from an observable method to assign it to a public variable for later use. Specifically, I need to retrieve this value and store it in the 'viewcount' variable for utilization in another function.

public viewcount:any;

public getcount(id){
  let view = " ";
  this.backandService.getViews(id).subscribe(
    (data:any) =>{
      view = data["0"].views;
      console.log(view);
    }
  );
  return view;
}

In another method, I attempt to use the returned value as follows:

public updateViews(id){
     let  view:any = this.viewcount;
       this.backandService.update('videos',id,
  {"viewcount":JSON.stringify(view)}).subscribe(
         data =>{
           console.log(data);
         }
       );
     }

However, despite my efforts, the value is never successfully returned for application in the 'updateViews' method. The console log displays XHR requests indicating a 404 not found error, with the request payload showing an empty bracket.

Answer №1

In order to assign a value to a module level variable, it must be a promise rather than just a number.

public viewCount: Promise<number>;

public requestCount(id){
  this.viewCount = new Promise<number>((resolve,reject) => {
    this.backandService.getViews(id).subscribe(
      (data:any) =>{
        let view = data["0"].views;
        console.log(view);
        resolve(view);
    });
   });
}

public async updateViews(id): Promise<void>{
  let view = await this.viewcount;
  this.backandService.update('videos',id { 
    "viewcount":JSON.stringify(view)}).subscribe(data =>{
       console.log (data);
     });
  });
}

An alternative method:

public updateViews(id): Promise<void>{
  return this.viewcount.then(view => ( 
    this.backandService.update('videos',id { 
      "viewcount":JSON.stringify(view)}).subscribe(data =>{
         console.log (data);
       });
    });
  })'
}

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

Controlling multiple bx-sliders with a single pager using only JavaScript

Is there a way to control 3 sliders using the same pager? I attempted to use the following code but it did not work: <script language="javascript"> $('.mobile_left_mble,.mobile_right_mble,.text_btn').bxSlider({ //pagerCustom: '#bx- ...

Error #301 in React: Infinite loop causing repeated rendering

import React,{createContext,useState} from 'react'; export const UserContext = createContext(); export const UserProvider = props =>{ const [ user,setUser ] = useState({ logged: false, User_info: { } }) if( ...

Extending the Model class in TypeScript with Sequelize

Currently, I am tackling a legacy project with the goal of transitioning it to Typescript. The project contains models that are structured as shown below: import Sequelize from "sequelize"; class MyModel extends Sequelize.Model { public static init(seq ...

What is the method for defining specific requirements for a generic type's implementation?

I am facing an issue with the following code snippet, where I am trying to restrict the pairing of Chart objects based on correct types for the data and options objects. However, despite my efforts, the TypeScript compiler is not throwing an error in the s ...

Issue with iPad Pro displaying Bootstrap 4 Navbar toggle icon

Having trouble with my Bootstrap 4.1.1 navbar on iPadPro. It's not displaying the correct data from the div and it's not collapsing properly. However, it works fine on small devices. Any suggestions on how to fix this issue? Here's the code ...

Is it possible to retrieve or modify the dimensions and position of an element set in a static position using only JavaScript?

Is it possible to access or modify the coordinates, width, and height of an element that is statically positioned using only JavaScript? If so, how can this be done in both pure JavaScript and jQuery? ...

What steps should I take to ensure my sanity studio updates are reflected in my nextjs app?

Upon configuring my sanity studio with the initial data, everything seemed to be working well. However, when I try to make changes and publish them, the next app still displays the previous data. Even after deleting some information in the studio, the upda ...

Submission form fails to go through or button for submitting is malfunctioning

After researching, I believed that this code would function properly. However, upon implementation, it is not working as expected. The main issue is that the form is failing to submit. How can I troubleshoot this problem? Furthermore, I am unable to re ...

Skrollr immediate pop-up notification

Can anyone help me figure out how to make text appear suddenly and then disappear using skrollr? I've been able to get it to fade in and out, but I want it to just show up without any transition. Here's the code I have so far: <div id="style" ...

Encasing a series of AJAX calls in a function: Implementing JavaScript and JQuery

I am facing an issue with a chain of two AJAX requests within a forEach() loop, where the second request relies on the response of the first. I have tried to wrap this code block in a function for reusability, but it seems to stop working. As a beginner in ...

Incorporating mapboxgl-spiderifier into your Angular project: A step-by-step guide

I am currently working on an angular application that utilizes mapbox with the help of ngx-mapbox-gl. I am looking to integrate it with mapboxgl-spiderifier, but I'm facing an issue as it doesn't have typings and I'm unsure how to include it ...

No input value provided

I can't figure out what's going wrong. In other js files, this code works fine. Here is my HTML code: <table class='table'> <tr> <th>Event</th><td><input class='for ...

Guide on transmitting data from a child component to a parent object in Vue.js?

When I attempt to utilize a child component with custom form inputs and emit those values to the parent component, I encounter an issue where one input value disappears when another input value is entered. Let me showcase some code: Child Component <tem ...

What would be the optimal type for the second argument of the `simulate` method?

When using the simulate function, I am familiar with code like this: simulate("change", { target: { value: '7' } }); However, if my onChange function requires an object as a parameter, what should I pass in the second argument? interface myObj ...

The ajax function nestled within a nested forEach loop completes its execution once the inner callback function is triggered

I am encountering a problem with an ajax call that is nested within a forEach loop inside another function. The issue is that the callback of the outer function is being triggered before the inner loop completes, resulting in "staticItemList" not being p ...

Troubleshooting the issue of conditional extension in Typescript for "Array or Object" not functioning as anticipated

My goal is to create a TypeScript type generic that has the following structure: type APIDataShape<T extends { id: unknown } | Array<{ id: unknown }>> = T extends Array<any> ? Array<{ id: T[number]["id"]; ...

The `react-hover` npm package functions flawlessly in the development environment despite being excluded from the production build

While working on my project, I decided to utilize the npm package react-hover and it's been effective during local development in dev build. However, when I execute the npm run build command to serve the production version, the components within the & ...

Error: Unable to locate module: Cannot find module './' in 'C:pathToFeeds'

Despite the numerous times this question has been asked before, none of the answers seem to apply to my specific situation. The issue I am encountering in my application is highlighted in the title: Below is the layout of my app's directory: https: ...

Navigating the jQuery Search Form: Redirecting to Pages within your Website

After successfully creating my first Javascript search form with an Autocomplete Script, I am facing a challenge. I want to enable users to press "enter" after searching for a product and get redirected to the corresponding product URL page. The operation ...

What is the quickest method for setting up types for node packages?

Whenever I need to use typed packages in my Node.js projects, there are two steps I have to take: Firstly, install the original package. For example: npm install express -S Secondly, install its type definition package. npm install @types/express -D I f ...