Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular5 Service call not working on ngOnInit

When I navigate to results component the service inside ngOnInit works as expected. Than I open the side menu, navigate to another page, then I navigate to the results page again. But this time the page don't render the results.The ng-template is rendered instead. No errors on console, nothing. The ngOnInit is working, is displaying the console.log('init'); But the service call don't. If I paste the service call inside the constructor or inside a function, it doesn't work too. I tried with and without ngZone, nothing..

I need to mention that if I press F5 directly on the Results page it works. Just when I navigate to it through the this.router.navigate(['/resultados']); Than it doesn't work.

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;
    }

}
like image 411
Rafael Natal Avatar asked Nov 22 '25 17:11

Rafael Natal


1 Answers

Using unsubscribe inside OnDestroy worked! Thank you @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();
    }
}
like image 175
Rafael Natal Avatar answered Nov 24 '25 07:11

Rafael Natal



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!