Error Uncovered: Ionic 2 Singleton Service Experiencing Issues

I have developed a User class to be used as a singleton service in multiple components. Could you please review if the Injectable() declaration is correct?

import { Injectable } from '@angular/core';
import {Http, Headers} from '@angular/http';
import { NavController, NavParams } from 'ionic-angular';
import { Facebook } from 'ionic-native';
import { HomePage } from '../../pages/home/home';

@Injectable()
export class User {
  public email;
  public pass;
  private token;
  private picture
  private fbToken              

  constructor(public http : Http){}

  public getEmail(){
    return this.email;
  }

  // more getters and setters.

The functionality works well with the first component (LoginPage)!

import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { RegisterPage } from '../register/register';
import { User } from '../../classes/singleton/user';

enum TpLogin {
    defLogin,
    fbLogin
}

@Component({
  selector: 'page-login',
  templateUrl: 'login.html'
})

export class LoginPage {          
    public tpLogin = TpLogin;    

    constructor(public navCtrl: NavController, public navParams: NavParams, public user : User){}            

    ionViewDidLoad() {}

    goHome(tpLogin : TpLogin){                
        var obj = this;                
        switch (tpLogin) {
            case TpLogin.defLogin : {obj.user.login(this.navCtrl); break;}          
            case TpLogin.fbLogin  : {obj.user.fbLogin(this.navCtrl); break;}
        }              
    }        
}

However, when I import the User class into other components and run the application, an error occurs:

Runtime Error Can't resolve all parameters for HomePage: ([object Object], [object Object], ?).

Note: I have imported the User service as a provider in appModule.ts, as shown below:

import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';
import { HttpModule } from '@angular/http';
import { MyApp } from './app.component';
import { LoginPage } from '../pages/Login/login';
import { RegisterPage } from '../pages/register/register';
import { HomePage } from '../pages/home/home';
import { InfoPage } from '../pages/info/info';
import { User } from '../classes/singleton/user';

@NgModule({
  declarations: [
    MyApp,
    LoginPage,
    RegisterPage,
    HomePage,
    InfoPage    
  ],
  imports: [
    BrowserModule,    
    HttpModule,
    IonicModule.forRoot(MyApp)
  ],
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    LoginPage,
    RegisterPage,
    HomePage,
    InfoPage    
  ],
  providers: [
    StatusBar,
    SplashScreen,    
    {provide: ErrorHandler, useClass: IonicErrorHandler},
    User
  ]
})
export class AppModule {}

Any assistance would be appreciated.

Answer №1

Here is the content of my HOME.TS file:

import { User } from '../../classes/singleton/user';
import { Component, ViewChild, ElementRef } from '@angular/core';
import { NavController } from 'ionic-angular';
import { InfoPage } from '../info/info';
import {Http, Headers} from '@angular/http';

declare var google;

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
    public barberList = [];    
    @ViewChild('map') mapElement: ElementRef;
     map: any;

  constructor(public navCtrl: NavController, public http: Http, public user : User) {      
        var url = 'https://cors-anywhere.herokuapp.com/http://98.111.45.209/barbearias';
        var headers = new Headers();          
        
        headers.append('Content-Type', 'application/json');           
        //headers.append('x-access-token', this.user.getToken());
        
        http.get(url,{headers: headers}).subscribe(res => {console.log(res.json().data);
                                                           this.barberList = res.json().data},
                                                   (err) => {console.log(err._body);});
  };

  ionViewDidLoad(){
    this.loadMap();
  };

  loadMap(){
 
    let latLng = new google.maps.LatLng(-26.334302,-48.8524027);
 
    let mapOptions = {
      center: latLng,
      zoom: 15,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    }
 
    this.map = new google.maps.Map(this.mapElement.nativeElement, mapOptions);
 
  }    

    getInfo(id,entity){    
        this.navCtrl.push(InfoPage,{allValues:{id:id,entity:entity}});        
    };
}

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

Revise directive following the dynamic addition of elements

My Objective: I aim to utilize directives for creating custom elements and dynamically inserting them into the view at various points in time. The Challenge: Upon dynamically adding custom elements to the view, they appear as raw HTML without the directi ...

Unable to fetch data from MongoDB in Node.js when using objectid

After passing objectid of hospital 1 from Postman to this program, it only returns an empty array. However, there is data that matches that objectid. Can you assist me in resolving this issue? When attempting to debug the program in the console, it shows t ...

Could there be an issue with the way I've implemented my setInterval function?

I am currently in the process of developing a stopwatch feature using React Native and implementing the setInterval function to increase a counter and update the state accordingly: Play Function (triggered upon pressing the play button) const [isRunning ...

Issues with Bootstrap Navigation Collapse Utilizing Data Attributes

I'm having trouble getting a Twitter Bootstrap 3 navbar to collapse using data attributes, as it is not expanding properly. Just to give some context, the project I am working on is an ASP.NET C# MVC project that runs on DNN (DotNetNuke) CMS. When I ...

Is it possible to access BreakpointObserver in Angular Material before the page has finished loading?

When utilizing the Angular BreakpointObserver in combination with Angular Material, I encounter an issue where the observer only triggers a change after it detects a difference. This becomes problematic on initial page load as there is no existing change t ...

Creating personalized headers for WebSocket in JavaScript

I am currently in search of a straightforward method to utilize WebSocket with custom headers for a web application, utilizing PHP as the backend and js+vuejs for the frontend. My application needs to establish a connection with a WebSocket server based o ...

Excellent Methods for Implementing a Double Click Functionality in JavaScript for Mouse

Is there a way to make the mouse double click by itself using JavaScript? I need this functionality for a Selenium project that requires testing, but unfortunately Selenium does not provide an option for double clicking. Can anyone suggest how I can achiev ...

Using postMessage to communicate with the localstorage of an iframe from a separate domain

I have a question regarding the challenges of using localStorage for performance reasons and any potential workarounds. From what I gather, once a reference to localStorage is detected on a page (at compile time?), it blocks the thread to read data from di ...

Tips for concealing mat-sidenav scrollbar in Angular Material

I've been trying to figure out how to hide the scrollbar in angular material mat-sidenav. I attempted to add overflow: hidden to the sidenav, but unfortunately, it didn't work as expected. Markup: <mat-sidenav-container class="sidenav-co ...

Is there a way to verify if a component contains a child node with the tag <template></template>?

Consider the scenario with MyComponent: <div [my-component]="'text'"></div> Within the code, I have access to this.viewContainerRef, which refers to the DOM node itself (<div>). However, for customization purposes, a user mig ...

Troubleshooting the issue with ajax loadXml callback functionality

My table is empty and I can't figure out where the mistake is. I want to use the console to debug, but I'm not sure how. Update: I found a working sample here http://www.w3schools.com/ajax/tryit.asp?filename=tryajax_xml2. I used similar code, bu ...

Retrieving the class name using jQuery

In my HTML code, there is a div with three classes defined as: <div class = "a b c"> .. </div> My goal is to access only the class b using the .attr() method. Is this achievable? ...

Initiate a fresh start with an automatic input reset

When you perform an action in the first id = "benodigheden", I believe there should be a specific outcome that then triggers a second rule for id = "benodigheden". However, I have been unsuccessful in finding information on this topic online. It seems like ...

Angular 4 animation causing children's styles to reset abruptly

Is there a way to maintain the fade-out effect of an element's child even after the animation ends? Currently, the child's style reverts back to its original state once the opacity animation completes. What can be done to prevent this behavior o ...

Is there a way to expand jQuery quicksearch functionality to include searching for words with accents?

Hello everyone, I'm currently working on the development of this website using jQuery isotope, WordPress, and jQuery quicksearch. Everything is functioning perfectly, but I would like to enhance its functionality. For example, when I type "Mexico," I ...

Learn how to render a single element with multiple child elements within separate `<td>` tags in a table row using React

I'm just starting out with React and I have a code snippet that I'm using to render an HTML table in a component. Is there a more optimized way to achieve this? bodyItems = sorted.map((data) => [ data.employerName, data.sectors.map((sector ...

Instructions on how to activate scrolling for a div element that becomes visible upon clicking a button

When a button in the navbar is clicked, a div appears with a height that exceeds the viewport/page size. How can I enable scrolling for the entire page when this happens? I attempted to use overflow: scroll, but it only applied scrolling to the internal d ...

Create a dynamic feature in Bootstrap4 where the navigation bar changes color as the user scrolls to different sections of the

Currently building my personal portfolio website with Bootstrap 4, I came up with a great idea: changing the navigation bar color based on different sections of the website. I attempted to achieve this using JQuery's offset and scrollTop functions, bu ...

Retrieve data from controller using jQuery Ajax

I am in need of assistance with my HTML form and controller interaction. I require a Boolean result from the controller based on user input. Here is an overview of my current form: <div id="temp"></div> @using (Html.BeginForm("Re ...

Fetching a JSON object from an external URL using JavaScript

Currently, I am working on a project using JavaScript and have an API that provides me with a JSON Object. You can access this JSON object by clicking on the following link: . Within this JSON object, there is a specific element located at JSONOBJECT.posi ...