3

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

}
Rafael Natal
  • 41
  • 1
  • 6
  • Sorry, but what in the *world* are you doing in that constructor? Delete all of those `this.router = router` methods, they're unnecessary. – Roddy of the Frozen Peas Feb 11 '18 at 02:04
  • Also you may want to read up on the [angular lifecycle hooks](https://angular.io/guide/lifecycle-hooks) and when each of those happens. OnInit is only called once after the first onChanges event. – Roddy of the Frozen Peas Feb 11 '18 at 02:07
  • Sorry it's because the page is not ready.. removed now.. Ok, but the problem is not the ngOnInit it is working. The service call inside it don't. – Rafael Natal Feb 11 '18 at 02:30
  • Please show firestoreService code – dev_in_progress Feb 11 '18 at 10:26
  • I think I had this once and ended up solving it by changing the RouteReuseStrategy, though I’m not sure if that was the right approach... my guess is if u were to unsubscribe to this OnDestroy, it would work properly – tam5 Feb 11 '18 at 13:41
  • @tam5 thank you very much. Unsubscribe OnDestroy worked like a charm! – Rafael Natal Feb 11 '18 at 15:18

1 Answers1

1

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();
    }
}
Rafael Natal
  • 41
  • 1
  • 6