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

The problem with the onClick event not triggering in Angular buttons

My issue revolves around a button in my code that is supposed to trigger a function logging the user out. However, for some reason, the event associated with it doesn't seem to be functioning at all. Here's the relevant code snippet: TS File: imp ...

Why is it that when the form is submitted, the value becomes unclear?

This is a form with HTML and TypeScript code that I am working on. <form> <div class="form-group"> <input class="form-control" ([ngModel])="login" placeholder="Login" required> </div> <div class="form-group"> &l ...

Allusion to a intricate data component

In my code, I have a model that is being represented by a class. For example, let's consider the model of a car: export class Car { public name : string; public color: string; public power : number; public service : boolean; } All c ...

Nest is unable to resolve the dependencies of the ItemsService. Ensure that the required argument at index [0] is present within the AppModule context

After following the Nest JS Crash tutorial from a Youtube Link, I encountered an error when importing an interface in the service. Nest seems unable to resolve dependencies of the ItemsService. It's important to ensure that the argument at index [0 ...

Sync user information when alterations are made on a different device

As I create a Discord clone using Next.js, I've encountered an issue where when a server is deleted, another client can still see and use the server until the page is reloaded. When testing out the official Discord web app, changes seemed to happen in ...

Please click twice in order to log in to Angular 16

Whenever I attempt to log in, I face the issue of having to click twice. The first click does not work, but the second one does. Additionally, an error message pops up: TypeError: Cannot read properties of undefined (reading 'name'). I am unsure ...

Angular: Enable function to await Observable completion before returning result

I require assistance with the user function below: getUser(uuid: string): Observable<WowUserDataModel> { let user: WowUserDataModel = { login: null, userUuid: uuid, firstName: null, lastName: null, displayName: nul ...

Prevent title flickering in Android using Ionic

I am attempting to create a tab content page using the "standard" method recommended by the ionic template example. However, I have noticed that when switching between tabs on Android, the view title flickers. This issue is not present on iOS or desktop b ...

Attempting to add a new property to every object in an array using TypeScript

In my Angular project, I have a specific code block that retrieves an array of objects containing contact records. Within a 'forEach' loop, I am generating a new field for each contact record to store the user's initials. The goal is to ad ...

What are the best practices for implementing MapLabel in an Angular project?

I need help displaying text on top of multiple polygons on a map. I've heard that Map Label can help with this, but I'm having trouble implementing it and can't find any NPM resources. Here is the Stack Blitz URL for reference: https://stac ...

What steps should I take to ensure that a cookie has been properly set before utilizing it?

I'm in the process of developing a JWT authorization code flow using Next.js and NestJS. Below is the POST request being sent from the frontend to the backend server: const response = await fetch( 'http://localhost:4000/auth/42/callback?code=& ...

Updating the navigation bar in Node/Angular 2 and displaying the sidebar once the user has logged in

I am facing a challenge with my first project/application built using Angular 2, particularly related to the login functionality. Here is what I expect from the application: Expectations: When I load the login component for the first time, the navbar ...

Angular Universal causing issues with updating the DOM component

@Component({ selector: 'mh-feature-popup', template: ` <div class="full"> <div> <div class="container-fluid" [@featurepop]="state"> <div class="row"> <div class="col-xs-12 col-md-4 col-md-offse ...

Maintain Angular Dropdown Menu Open Across Page Refresh

I am currently working on an HTML/Typescript view that is connected to a SQL Database. Whenever there are changes made to the database, the entire webpage reloads. The issue we are facing is that we have dropdown menus on the page that clients want to rema ...

The sign out option fails to erase the data stored in Local Storage

After implementing a login feature that stores a token in local storage, I encountered an issue with the logout button. The intention was for the button to delete the token from local storage and set the user to null upon clicking it. However, this functio ...

Is app.component.ts necessary in an Angular 2 project?

Currently diving into Angular 2 and have a burning question on my mind. Do I really need the app.component.ts file in my project? Each of my folders has its own component and template, so I'm debating if the main component is necessary or if I can rem ...

Angular: The type AbstractControl<any> cannot be assigned to type FormControl

I am working with a child component that includes an input tag <input [formControl]="control"> component.ts file @Input() control: FormControl; In the parent component, I am using it as follows: <app-input [control]="f['email ...

Issue with mssql.connect await causing timeout in Jest

Testing some functionality in a nextjs Typescript project that needs to interact with the database directly, not relying on mocked sql query results. But encountering issues with it actually writing to the database. A brief example of the problem: /* @/li ...

Encountering a service error that results in the inability to read properties of undefined when passing a method as a

Whenever I attempt to pass a service function as a parameter to another function, an error 'Cannot read properties of undefined myService' occurs during execution. However, calling this.myService.method() individually works perfectly fine without ...

Utilizing Filters (Pipes) in Angular 2 Components without Involving the DOM Filters

When working in Angular 1, we have the ability to use filters in both the DOM and Typescript/Javascript. However, when using Angular 2, we utilize pipes for similar functionality, but these pipes can only be accessed within the DOM. Is there a different ap ...