The initial page in Ionic 2 encounters issues with HTTP requests not functioning properly

I have created a basic app using the side menu template along with a provider called conexao-home.ts. Within a new page named teste, I have implemented a function called buscarUsuarios (linked to a button), which in turn calls the getRemoteUsers function within the provider.

In the ionViewDidLoad lifecycle hook, I have also included a call to the getRemoteUsers function. However, when the teste page is loaded, it successfully makes the HTTP call but doesn't return the data read back into the variable.

Interestingly, clicking the button triggers the function and displays the fetched data on the page. How can this issue be resolved?

teste.ts

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { ConexaoHome } from '../../providers/conexao-home';

@Component({
  selector: 'page-teste',
  templateUrl: 'teste.html',
})
export class Teste {

  public users: any;
  public teste: any;

  constructor(public navCtrl: NavController, public navParams: NavParams, public conexaoServico: ConexaoHome) {

  }

  buscarUsuarios() {
    this.users = this.conexaoServico.getRemoteUsers('Fetching users');
    console.log('calling...');
    console.log(this.users);
    console.log('returning...' + this.users);
  }

  buscar() {
    this.teste = this.conexaoServico.getRemoteTeste('testing...');
    console.log(this.teste);
  }

  ionViewDidLoad() {
    console.log('ionViewDidLoad Teste');
    //this.buscarUsuarios();
    this.users = this.conexaoServico.getRemoteUsers('Fetching users');
    console.log(this.users);
  }

}

teste.html

<ion-header>
  <ion-navbar>
    <button ion-button menuToggle>
      <ion-icon name="menu"></ion-icon>
    </button>
    <ion-title>Teste</ion-title>
  </ion-navbar>
</ion-header>

<ion-content padding="false">
  <button ion-button (click)="buscarUsuarios()">Fetch Data</button>
  <br>
  <button ion-button (click)="buscar()">Fetch Data 2</button>
  {{ teste }}
  <br>
  <ion-list>
    <button ion-item *ngFor="let user of users">
      <ion-avatar item-left>
        <img src="{{ user.picture.medium }}">
      </ion-avatar>
      <h2 text-wrap>{{ user.name.title }} {{ user.name.first }} {{ user.name.last }}</h2>
      <h3 text-wrap>{{ user.email }}</h3>
    </button>
  </ion-list>
</ion-content>

provider conexao-home.ts

import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';

@Injectable()
export class ConexaoHome {

  public usuarios: any;
  public areas: any;

  constructor(public http: Http) {
    console.log('Hello ConexaoHome Provider');
  }

  getRemoteUsers(tipo) {
    this.http.get('https://randomuser.me/api/?results=10').
    map(res => res.json()
    ).subscribe(data => {
      console.log(data.results);
      console.log(tipo);
      this.usuarios = data.results;
    });
    return this.usuarios;
  }

  getRemoteTeste(tipo) {
    console.log(tipo);
    return ('test executed 2');
  }
}

Thank you.

Answer №1

You shouldn't approach it that way:

getRemoteUsers(type) {
    this.http.get('https://randomuser.me/api/?results=10').
    map(res => res.json()
    ).subscribe(data => {
      console.log(data.results);
      console.log(type);
      this.users = data.results;
    });
    return this.users;
}

This may lead to a premature return statement before the asynchronous call is completed. The reason being, you're making an asynchronous http request via Observable. It's worth delving more into this concept here

Instead, consider something along these lines:

getRemoteUsers(type) {
    return this.http
      .get('https://randomuser.me/api/?results=10')
      .map(res => res.json())
}

Then, utilize it in this manner:

ionViewDidLoad() {
    this.connectionService.getRemoteUsers('Fetching users').subscribe((data) => { 
       this.users = data;
       console.log(this.users);
    });
}

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

It appears that using dedicated objects such as HttpParams or UrlSearchParams do not seem to work when dealing with Angular 5 and HTTP GET query parameters

I'm facing a perplexing issue that I just can’t seem to figure out. Below is the code snippet making a call to a REST endpoint: this.http.get<AllApplicationType[]>(environment.SUDS_API_SERVICE_URL + environment.SUDS_ALL_APPLICATIONS_URL, this ...

Exploring the possibilities of combining AngularJS and Angular 2 routing with wildcard paths

I'm struggling with wildcard path routing in an app that's partially upgraded from AngularJS to ng2. Combining both types of routing involves the following: The initial step in creating a dual router setup is to include an Angular root comp ...

Issue with Ionic 2 where headers are not being properly set before making an HTTP request

I am currently working on a request to my backend system that involves setting up headers and tokens. The code I have written for this process is as follows: loggedIn() { let headers = new Headers(); headers.append('Content-Type', ' ...

Calculating the frequency of a variable within a nested object in an Angular application

After assigning data fetched from an API to a variable called todayData, I noticed that there is a nested object named meals within it, which contains a property called name. My goal is to determine the frequency of occurrences in the name property within ...

The loading spinner feature in the UI Route does not function properly unless the $timeout component is included

In my Angular application that uses UI Router, I have set up subscriptions to the $stateChangeStart and $stateChangeSuccess events. Within these event handlers, I am toggling a controller property called "isLoading" to show or hide a loading indicator outs ...

Difficulty Resolving Parameter Resolution in Angular 5 Shared Library Module ([object Object], ?, ?)

I'm facing an issue while attempting to integrate a custom shared component library into my Angular application, which has been upgraded from Angular 5 to Angular 4. Unfortunately, I am unable to resolve the problem at hand. The error message I&apos ...

guide on implementing optional URL parameters in NestJS

Currently, I am in the process of transitioning to the Nestjs library for our backend service. I am looking to create a route that includes 2 optional parameters in the URL. Here's what I have in mind: /route/:param1/config/:OptionalParam3?/:Optional ...

Angular directive that replaces content with into an attribute

TL;DR; I am looking to create a directive that replaces the innerHtml of a tag with another tag attribute and ensure it is compiled. The expression is within an ng-repeat, which seems to be crucial. <ii>{{exp}}</ii> -> <i title="exp c ...

The type does not have a property named 'defaultProps'

I have a Typescript React class component structured like this: import React, { Component } from 'react'; interface Props { bar?: boolean; } const defaultProps: Partial<Props> = { bar: false, }; class Foo extends Component<Props& ...

Troubleshooting issues with Angular integration in Laravel

I'm facing an issue with implementing simple angular code in Laravel. Surprisingly, it works fine when tested on Codepen. In my gulp file, I have included Angular and tried isolating it by commenting out all other scripts to test only with Angular. ...

Ways to update the contents of an individual div within an ng-repeat loop

I am currently working on some Angular code. <div ng-repeat="item in items | filter:search" class="container"> <h3>{{item.name}}</h3> <p>category:{{item.category}}</p> <p>price:INR {{ ...

A collection of radio button groupings organized using ng-repeat

I have a collection of objects containing nested arrays of objects. I need to organize these objects into groups based on the number of parent objects, each group needing radio buttons corresponding to the number of child objects. Here is an example of th ...

Navigating the conundrum of Express routing in HTML5 style without using HASHBangs can be challenging when using Angular JS and Ye

Starting a new project from scratch and diving into the world of Yeoman's modern workflow tools for front-end development with AngularJS. The backend will be written in Node.js using Express, with a focus on serving all content statically to the clien ...

The issue with zone.js remains unresolved

Since updating to the most recent version of Angular cli, I have encountered an error when trying to run ng serve: ./node_modules/@angular-devkit/build-angular/src/webpack/es5-polyfills.js:106:0-37 - Error: Module not found: Error: Can't resolve &apo ...

How can an array of file paths be transformed into a tree structure?

I am looking to transform a list of file and folder paths into a tree object structure (an array of objects where the children points to the array itself): type TreeItem<T> = { title: T key: T type: 'tree' | 'blob' childr ...

Discovering elements containing a particular value within a deeply nested array of indefinite depth

I am working with an array containing objects that may have unknown and varying nesting depths. Here is an example of such an array: let exampleArray = [ { id: 'some-id', label: "Item 1", children: [ { id: &a ...

Learn how to dynamically disable or hide the "Today" button in an angular-ui datepicker based on whether it is the weekend

What is the process to hide or disable the "Today" button based on a condition, for example, if today is a weekend? The goal is to conceal the "Today" button in such scenarios. <div class="form-group"> <div class="input-group datePicker"> ...

Ensuring equality of values in Angular2 reactive forms

I'm currently working on an Angular2 Reactive form that requires users to confirm their email address. You can check out the plunker for reference here import { Component, OnInit } from '@angular/core'; import { FormControl, FormGroup, Vali ...

You have encountered an issue with the runtime-only build of Vue, which does not include the template compiler

Lately, I have been utilizing Vue in a project and encountered an issue where upon compiling, my browser page displays as white with an error message stating "You are using the runtime-only build of Vue where the template compiler is not available. Either ...

Discovering the data type in Typescript through the use of Generics

In my data structure, I am using generics to build it. However, when I try to populate data, I encounter the need to convert simple formats into the correct types. The issue arises as the class is configured with Generics, making it difficult for me to det ...