Troubleshoot: Angular5 Service call not functioning properly when called in ngOnInit

Every time I go to the results component, the service inside ngOnInit behaves as expected. However, when I open the side menu, navigate to another page, and then return to the results page, the page fails to render the results. Instead, the ng-template is displayed. There are no errors in the console, nothing at all. The ngOnInit function is working fine; it displays the console.log('init'). But for some reason, the service call doesn't work. I've tried putting the service call inside the constructor or a separate function, but it still doesn't work. I even tested using NgZone, but that didn't help either.

It's worth noting that if I press F5 directly on the Results page, everything works perfectly. It's only when I navigate to it using

this.router.navigate(['/resultados']);
that things go wrong.

This is the Results component:

import { Component, OnInit, NgZone } from '@angular/core';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import { NavService } from '../shared/nav.service';
import {AngularFirestore} from 'angularfire2/firestore';
import {firestoreService} from '../shared/firestore.service';
import {Usuario} from '../../models/usuario'

@Component({
    selector: 'resultados',
    templateUrl: 'resultados.component.html'
})

export class ResultadosComponent implements OnInit {
    servId:any;
    users: Usuario[];
    constructor(
        private fService: firestoreService,
        private service:NavService,
        private router: Router,
        private zone: NgZone
      ) { }

    ngOnInit() { 
        console.log('init')
        this.fService.getUsers().subscribe(users=>{
            this.zone.run(()=>{
                this.users = users;
            })

        })
    }
}

This is the Results HTML:

<div class="resultados" *ngIf="users?.length > 0;else noUsers"> 
<ul *ngFor="let user of users">
    <li>{{user.uid}}</li>
</ul>
</div>
<ng-template #noUsers>
<hr>
<h5>Nenhum usuário cadastrado</h5>
</ng-template>

This is the firestore.service:

    import { Injectable } from '@angular/core';
    import {AngularFirestore, AngularFirestoreCollection, 
    AngularFirestoreDocument} from 'angularfire2/firestore';
    import {Usuario} from '../../models/usuario'
    import {Observable} from 'rxjs/Observable';


@Injectable()
export class firestoreService {
    usersCollection: AngularFirestoreCollection<Usuario>;
    users:Observable<Usuario[]>;

     constructor(public afs:AngularFirestore){

         this.users = this.afs.collection('users').valueChanges();

     }

    getUsers(){
        return this.users;
    }

}

Answer №1

Implementing the unsubscribe method within OnDestroy was successful! Special thanks to @tam5.

import { Component, OnInit, NgZone } from '@angular/core';
import { Router, ActivatedRoute, ParamMap } from '@angular/router';
import { NavService } from '../shared/nav.service';
import {AngularFirestore} from 'angularfire2/firestore';
import {firestoreService} from '../shared/firestore.service';
import {Usuario} from '../../models/usuario'
import { OnDestroy } from '@angular/core/src/metadata/lifecycle_hooks';
import { Subscription } from 'rxjs/Subscription'; //<== added this

@Component({
    selector: 'resultados',
    templateUrl: 'resultados.component.html'
})

export class ResultadosComponent implements OnInit , OnDestroy {
    servId:any;
    users: Usuario[];
    private subscription: Subscription = new Subscription(); //<== added this

    constructor(
        private fService: firestoreService,
        private service:NavService,
        private router: Router,
        private zone: NgZone
      ) {


      }

    ngOnInit() { 
        console.log('init')
    this.subscription.add(this.fService.getUsers().subscribe(users=>{ //<== added this

            this.zone.run(()=>{
                this.users = users;
            })

        }))
    }

    ngOnDestroy(){ //<== added this
        this.subscription.unsubscribe();
    }
}

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

Troubleshooting Angular 2 routes failing to function post aot compilation deployment

Currently, I am implementing RouterModule in my project and have the following configuration in my app.module.ts file: const appRoutes: Routes = [ { path: '', redirectTo: 'mainMenu', pathMatch: 'full' }, { path: 'mainMen ...

Conceal the visibility of the eye icon within the password field in Angular 6

The current implementation of the function is operational, although it involves using a checkbox. I am seeking assistance regarding incorporating an eye icon within the password input field, preferably without relying on bootstrap or font-awesome. Any gu ...

Exploring Objects using Typescript

I need help creating a mapper for objects that allows TypeScript to recognize the returned type correctly. For example: type ExampleObject = { text: string; // this object may have properties of any type number: number; }; const object: ExampleObjec ...

There seems to be an issue with the subscription of a subject between two modules in Angular 5

Currently, I am in the process of developing a project using Angular 5. One requirement is to display an app loading spinner frequently. To achieve this, I have created a shared module along with a spinner component within it. Below is the content of my mo ...

Is there an alternative course of action since determining if Observable is empty is not feasible?

I am diving into Angular 11 and exploring the world of Observables and Subjects as a beginner. Within my application, I have a mat-autocomplete component that organizes its results into categories. One of these categories is dedicated to articles, and I&a ...

Accessing images hosted on an IIS server from a client using a URL in an ASP .Net application

My application is built using Api ASP.Net, and I store the images in the "wwwroot" directory Content https://i.sstatic.net/JP2Lx.png After publishing my application, the folder structure remains intact and I need to be able to access the images through ...

The FaceBook SDK in React Native is providing an incorrect signature when trying to retrieve a token for iOS

After successfully implementing the latest Facebook SDK react-native-fbsdk-next for Android, I am facing issues with its functionality on IOS. I have managed to obtain a token, but when attempting to use it to fetch pages, I keep getting a "wrong signature ...

Ways to avoid redundancy in Gitlab CI/CD when utilizing multiple stages

Currently, my workflow involves utilizing gitlab CI/CD for deploying my angular app on firebase. This process consists of 2 stages: build and deploy. image: node:11.2.0 stages: - build - deploy cache: paths: - node_modules/ build: stage: bu ...

Angular 2 - Implementing a custom base view for all components within a specific directory

I'm currently working on an app that involves user authentication. Once users are logged in, they should have access to an admin sidebar for navigation. However, there are certain pages like Login and Register that won't require the sidebar. Furt ...

Incorporating data from an api call to establish the starting state of a react component

I have been delving into the world of React and TypeScript while working on a fun project - a word guessing game inspired by Hangman. In this game, players have 5 chances to guess the correct word, which is retrieved from an API call. I populate an array w ...

Angular : How can a single item be transferred from an array list to another service using Angular services?

How to Transfer a Single List Item to the Cart? I'm working on an Angular web application and I need help with transferring a single item from one service to another service and also displaying it in a different component. While I have successfully i ...

Verification based on conditions for Angular reactive forms

I am currently learning Angular and working on creating a reactive form. Within my HTML table, I have generated controls by looping through the data. I am looking to add validation based on the following cases: Upon page load, the Save button should be ...

What is the proper way to specify the type for a proxy that encapsulates a third-party class?

I have developed a unique approach to enhancing Firestore's Query class by implementing a Proxy wrapper. The role of my proxy is twofold: If a function is called on the proxy, which exists in the Query class, the proxy will direct that function call ...

The data type 'string | undefined' cannot be assigned to the data type 'string' when working with .env variables

Trying to integrate next-auth into my nextjs-13 application, I encountered an error when attempting to use .env variables in the [...nextauth]/route.ts: Type 'string | undefined' is not assignable to type 'string'. https://i.stack.im ...

Tips for distinguishing a mapped type using Pick from the original type when every property is optional

I am working with a custom type called ColumnSetting, which is a subset of another type called Column. The original Column type has most properties listed as optional: type ColumnSetting = Pick<Column, 'colId' | 'width' | 'sort ...

How to apply a CSS class to the body element using Angular 2

I am working with three components in my Angular application: HomeComponent, SignInComponent, and AppComponent. The Home Page (HomeComponent) is displayed when the application is opened, and when I click the "Sign In" button, the signin page opens. I want ...

Issue with mediaRecorder.ondataavailable in Angular 4 - need a solution

Currently, I am attempting to transmit real-time streaming data from an Angular 4 application to a NodeJS server. To achieve this, I have implemented the usage of socket.io and webRtc for streaming. constructor(private _chatService: ChatService) {} ngOnI ...

Is a special *ngFor required when implementing Angular2 with Nativescript?

My current project involves creating a mobile app that requires listing a few labels. Here is the code snippet: @Component({ selector: 'code-m', template: ` <StackLayout dock="top" orientation="vertical" style="height: ...

What is the method for inserting a specific index into an interface array in TypeScript?

In my angular(typescript) application, I have an interface defined as follows: export interface PartnerCnic{ id: string; shipperRegCnicFront: File; shipperRegCnicBack: File; } Within my component, I have initialized an empty array for this interface li ...

The expected input should be either an HTMLElement or an SVGElement, but the received input is currently null

Below is the code for a component: function SignUpPage() { return ( <> <h1>Sign Up</h1> <input name="userName" /> </> ); } export default SignUpPage; Testing the component: it("should c ...