Discovering the worth of a variable outside of a subscription or Promise within Ionic 3

Apologies for my English.

I am encountering an issue when attempting to view the results of a REST API using both subscribe and Promise methods.

Within my provider, I have the following code:

Provider:

import { HttpClient } from '@angular/common/http';
import { Injectable } from '@angular/core';
import 'rxjs/add/operator/toPromise';

@Injectable()
export class UserServiceProvider {

   path : string  = 'my_paht_remote';

  constructor(public http: HttpClient) {
    console.log('Hello UserServiceProvider Provider');
  }

  getUsers() {

    return this.http.get(this.path');

  }

  getList()
  {
    return new Promise ( resolve => {
      this.http.get(this.path).subscribe(
        data => {

          resolve(data);
        }, err => {
          console.error();
        }

      );


    } );
  }

}

Now, in the TypeScript file:

--Imports
...
import { UserServiceProvider } from '../../providers/user-service/user-service';
...
export class CaicesPage {

users: any;
users2: any;
   ...
ionViewDidLoad()
  {
    this.showMap();  //This is a function for viewing Google Maps. 
  }

showMap()
  {
    //Here I should be able to see the result of the remote JSON File:

       this.userService.getUsers().subscribe(
        (data) => { // Success
          this.users = data['results'];   

        },
        (error) =>{
          console.error(error);
        }
      );

     console.info(this.users); // I am seeing 'Undefined', Why ?

   //With the following approach, I can also view the contents of the JSON File:
   this.userService.getList().then(

      data => {

        this.users2=data['results'];

      }
    );

    console.info(this.users2); // Again, I see 'Undefined', Why ?

   }


}

How can I access the values of var users or var users2 outside of subscribe or then functions?

Your assistance is greatly appreciated.

Answer №1

When displaying the variable in the success branch, you may wonder if you'll see a value that confirms your service is returning the correct result. For example:

showMap()
{
//Here I can see the result of JSon File remote:

   this.userService.getUsers().subscribe(
    (data) => { // Success
      this.users = data['results'];   
      console.info(this.users); <=============== HERE


    },
    (error) =>{
      console.error(error);
    }
  );

It's important to note that you won't see a value with the log in its original position because the code executes immediately after the call to subscribe, before the service has actually returned a value.

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

Angular 2 fails to redirect to a 404 page if both the route parameter and address are not valid

Currently, while working on my application with Angular 4.1.1, I have a habit of declaring routing in every module I create. For instance, in the file new-cars.routing.module.ts: import { NgModule } from '@angular/core'; import { RouterModule, ...

Pass down properties to a React component

Currently, all my SVCs are created as react components and I would like the ability to pass a color attribute as a prop to override the default color of the components. However, using props attribute results in an unattractive object that needs to be defin ...

What are the best techniques for concentrating on a kendo maskedtextbox?

What is the correct way to set focus on the kendo-maskedtextbox in TypeScript after the view has initialized? The information provided in Telerik's example here is lacking in detail. ...

Testing NestJS Global ModulesExplore how to efficiently use NestJS global

Is it possible to seamlessly include all @Global modules into a TestModule without the need to manually import them like in the main application? Until now, I've had to remember to add each global module to the list of imports for my test: await Tes ...

Tips for syncing the state data stored in local storage across all tabs with Ngxs state management

After converting the state data to base64 format using the Ngxs state management library, I am saving it. While I can retrieve all data across different tabs, any changes made in one tab do not automatically sync with other tabs. A tab refresh is required ...

Deactivate additional fields when choosing an option from the drop-down selection menu

When designing a form with a select dropdown that displays various options, I encountered an issue. I want to disable certain fields if a specific option is chosen from the dropdown. For instance, if "Within Company" is selected in the transaction type, I ...

Angular 2 experiencing issues with the authorization header

Hello there! I am currently working with the Ionic 2 framework alongside Angular, and I'm facing an issue while trying to make an HTTP request with the authorization header. It seems like the header is not being sent properly. Can someone help me iden ...

Looking for an Ionic 3 search function to filter a JSON array?

I am currently developing a market app using ionic 3, and one of the key features is the "products" list. Instead of manually inputting data, my "products page" retrieves items from a JSON array through an HTTP post request: postProducts(type){ return th ...

Developing an Angular 11 Web API Controller with a POST Method

I am in need of creating or reusing an object within my web API controller class to send these 4 variables via a POST request: int Date, int TemperatureC, int TemperatureF, string Summary Currently, I am utilizing the default weather forecast controller t ...

Upgrading to React Router v6: Implementing Loader Functions with Context API

Having issues implementing loaders in React-Router V6 while making a request for a page through a function located in the context file. Unfortunately, I can't access the context from main.js where the router is defined. Main.js import ReactDOM from & ...

What is the best way to create a personalized filter function for dates in JavaScript?

I am working with a DataTable that includes a column called Timestamp: <p-dataTable sortMode="multiple" scrollable="scrollable" scrollHeight="150" [value]="currentChartData" #dt> <p-column field="timestamp" header="Timestamp" [sortable]=" ...

The default value of components in Next.js

I'm working on establishing a global variable that all components are initially rendered with and setting the default value, but I'm unsure about how to accomplish the second part. Currently, this is what I have in my _app.tsx: import { AppProps ...

"Create a separate function for the pipeable operator in RXJS for enhanced code

After working on some code, I came up with the following implementation this.form.valueChanges.pipe( take(1), map(val => // doSomething), exhaustMap(val => // someInner observable logic return of({someValue}) ) ).subscrib ...

Using Fixed Patterns and Combining Types in an Interface

Presently, I am working with this interface: export interface User{ name: string birthday: number | Timestamp ... } When strictTemplates:false is enabled, I have no issue using this interface for server data retrieval with the birthday parameter in ...

Discover the magic of observing prop changes in Vue Composition API / Vue 3!

Exploring the Vue Composition API RFC Reference site, it's easy to find various uses of the watch module, but there is a lack of examples on how to watch component props. This crucial information is not highlighted on the main page of Vue Composition ...

A class definition showcasing an abstract class with a restricted constructor access

Within my codebase, there is a simple function that checks if an object is an instance of a specific class. The function takes both the object and the class as arguments. To better illustrate the issue, here is a simplified example without delving into th ...

Using Angular 5 to make a series of API calls, fetching a large object while also updating the UI with progress

I'm currently working on an Angular 5 Project where speed and responsiveness are crucial when retrieving a large object from the server. To optimize performance, I have broken down the object (resembling a Word Document) into main components (similar ...

What is the best way to use Immer to update Zustand state when incorporating objects that are added through a controlled form using React-Hook-

Having some trouble with integrating Zustand and Immer using React-Hook-Form. My goal is to capture a series of values from a form, store them in a list, and allow for the addition of new objects to that list. In this scenario, the user inputs data for a ...

Steps for Properly Defining Next.js getServerSideProps as a Function Declaration

I've been working on implementing getServerSideProps (additional information available here, and detailed API documentation here), but my challenge lies in utilizing it as a function declaration instead of an expression. Despite searching for relevant ...

What is the best way to rid ourselves of unwanted values?

In the laravel-vue-boilerplate package, there is a User CRUD feature. I duplicated this functionality to create an Item CRUD by making some changes and adjustments. Everything is working fine except for one issue: after editing an item, when trying to add ...