Having trouble integrating a Service as a provider in app.component.ts

I'm in need of adding a provider to facilitate sharing a variable with app.component.ts. My goal is to access the logged-in user data in real time within my app, but I'm struggling to correctly implement the provider in the constructor, resulting in the following error message:

Error: No Firebase App '[DEFAULT]' has been created - please call Firebase App.initializeApp()

Below is an overview of my code setup:

app.component.ts :

import { UsersServiceProvider } from '../providers/users-service/users-service';
@Component({
  templateUrl: 'app.html',
})

export class MyApp {
    @ViewChild(Nav) navCtrl: Nav;
    rootPage:any = InicioPage;

    constructor(public userServices : UsersServiceProvider) // along with other imports
    platform.ready().then(() => {
      statusBar.styleDefault();
      splashScreen.hide();
    });
    var config = {
         //configurations for the app and firebase
    };
    firebase.initializeApp(config);
    var that = this;
    firebase.auth().onAuthStateChanged((user) => {
        if (user) {
        // Need to assign the variable on userServices HERE
        }
    })
};

user-service.ts

import { Injectable } from '@angular/core';
import {AlertController , Platform} from 'ionic-angular'
import { Http } from '@angular/http';
import 'rxjs/add/operator/map';
import * as firebase from 'firebase';

@Injectable()
export class UsersServiceProvider {

public currentUser : any;
 constructor(private platform: Platform, public alertCtrl: AlertController, public http: Http) {
}

setCurrentUser(user){
  this.currentUser = user; // should be set here
}

}

All configurations are also properly set up in app.module.ts

Answer №1

Below is an example of how you can invoke the setCurrentUser() method within your UsersServiceProvider using MyApp:

this.userServices.setCurrentUser(user);

Here is how it fits into the larger context:

import {
  UsersServiceProvider
} from '../providers/users-service/users-service';
@Component({
  templateUrl: 'app.html',
})

export class MyApp {
  @ViewChild(Nav) navCtrl: Nav;
  rootPage: any = InicioPage;

  constructor(public userServices: UsersServiceProvider) //additional imports included
  platform.ready().then(() => {
    statusBar.styleDefault();
    splashScreen.hide();
  });
  var config = { //various configurations for the app and firebase
  };
  firebase.initializeApp(config);
  var that = this;
  firebase.auth().onAuthStateChanged((user) => {
    if (user) {
      this.userServices.setCurrentUser(user); // Ensure that the userServices variable is set HERE
    }
  })
};

Answer №2

While I may not be well-versed in utilizing Firebase, have you attempted to integrate the service within app.module.ts? This step is essential before being able to inject it into any class. The structure should resemble the following:

@NgModule({
declarations: [],
imports: [],
providers: [UsersServiceProvider]
}) 

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 error message "@types/d3" states that the type 'Area<X>' cannot be assigned to the type 'String'

Within a typescript class, I have a method instance... createArea = d3.area<Point>().x((d) => d.x).y0((d) => d.max).y1((d) => d.y); Although this method works fine, it is being seen as an instance field. To rectify this, I tried adding a t ...

Creating a TypeScript generic that can traverse the routes configuration tree while accumulating the path is a useful skill to have

I am struggling with defining a TypeScript generic to achieve a specific output. type Route = { path: string children?: readonly Route[] } const root = { path: "a", children: [ { path: "b" }, { path: "c", chil ...

Issue with Loosing Focus in React TextInput when typing the letter "S"

My TextInput is acting strangely - it loses focus only when I type the letter s. All other letters work fine. <FormControl key={"1"} sx={{ m: 1 }} variant="outlined" onChange={handleFilterValueChange}> <InputLabel htmlFor=& ...

Encrypting data in Typescript within an Angular application and decrypting it in Java

Currently utilizing Angular7 and client provided me with Java encryption and decryption code that I need to implement in Angular. Java code snippet: import java.security.SecureRandom; import java.security.spec.KeySpec; import java.util.Base64; import ja ...

What steps are involved in switching the package manager for the Angular CLI, for example, replacing npm with pnpm when using `ng add`?

I couldn't find a lot of information on this topic, so I decided to ask a question on Stack Overflow. When it comes to commands like ng add @angular/material, I prefer using the package manager pnpm. ...

Detecting page scrolling in Angular can be a challenging task

Having some issue with detecting scroll events in Angular. Here's the code snippet: @HostListener("window:scroll", []) onWindowScroll() { console.log("hello"); } Can anyone spot what I'm doing wrong? ...

What is the process for importing type definitions from a custom module?

I am struggling with a particular issue and finding it difficult to search for a solution. Here is the problem: I have created a TypeScript class that I am exporting: class MyAPIClass { myMethod(one:number) : void; secondMethod(text:string) : number; ...

Angular4 Error: Unable to link to 'ngClass' as it is not recognized as a property of 'input'

Currently, I am facing an issue in my project where I am utilizing lazy loading. Specifically, within my registration module, I am attempting to utilize the [ngClass] directive to append an 'invalid' class when there are validation errors present ...

How can I extend a third-party JavaScript library in TypeScript using a declaration file?

Currently, I am working on creating a .d.ts file for an external library called nodejs-driver. While I have been able to map functions and objects successfully, I am struggling with incorporating the "inherit from objects defined in the JS library" conce ...

What is the importance of feature modules exporting shared dependencies in AngularJS?

I've recently been diving into a tutorial about feature modules, which can be found here: . One thing that caught my attention is how the tutorial imports and then exports FormsModule in shared.module.ts. I'm curious as to why this is done. Fur ...

Icon missing from Android status bar in Ionic 3

After updating my project's ionic version, I noticed that the android app's status bar no longer displays any icons when entering the app: https://i.sstatic.net/z8Gf9.png Here is how it looks when entering the app: https://i.sstatic.net/jfnAB. ...

Unable to capture errors during input validation in Angular 6

My form is designed to validate user input to check if it meets minimum length requirements, displaying an alert if it doesn't. While there may be additional validation checks needed in the future, the initial check for minlength is not functioning co ...

Retrieve all exports from a module within a single file using Typescript/Javascript ES6 through programmatic means

I aim to extract the types of all module exports by iterating through them. I believe that this information should be accessible during compile time export const a = 123; export const b = 321; // Is there a way to achieve something similar in TypeScript/ ...

implement dynamic interaction between two dropdown menus in angular 4

uniqueComponent.html <select data-placeholder="All Categories" class="category" value="category.category.categoryName"> <option selected="selected" style="display:none">Select Category</option> <option class="select" *ngFor="let c ...

Vetur is experiencing issues with template functionality, such as not properly checking data and methods

I have incorporated the vetur extension into my Visual Studio Code for a Vue project using TypeScript. I recently discovered that vetur has the capability to perform type checks within the template tag for props, methods, and even variables. However, in ...

Is it possible to establish a connection between Firebase Storage and HTML using TypeScript without Angular or React in IntelliJ?

My project goal is to create a functional login and register page using TypeScript. Currently, my code operates without a database, but I aim to implement Firebase for registering user credentials for easy login. I have only come across tutorials using F ...

The impact of redefining TypeScript constructor parameter properties when inheriting classes

Exploring the inner workings of TypeScript from a more theoretical perspective. Referencing this particular discussion and drawing from personal experiences, it appears that there are two distinct methods for handling constructor parameter properties when ...

Issue with Angular App: Bootstrap navbar not displaying on smaller screens

I am working on an Angular app (using Angular 11.2.4 with Bootstrap 4.5.3) and facing an issue where the navbar is not rendering correctly on screens smaller than ~580 pixels wide. Even when I click the toggler to 'expand' the collapse region, n ...

NG2-Charts are not rendering until the page is manually refreshed

I am currently working on an Angular project utilizing Angular 11. The issue I am encountering pertains to ng2-charts. Essentially, the chart is populated with data from an api-request call to the backend. I have identified where the problem lies, but I ...

Set up a new user account in Angular 5 Firebase by providing an email address and password

My goal is to create a new user with an email, password, and additional data such as their name. This is how my user interface looks: export interface UserInterface { id?: string; name: string; email: string; password: string; status: string ...