Angular5服务调用不适用于ngOnInit

时间:2018-02-11 02:02:05

标签: angular typescript ngoninit

当我导航到结果组件时,ngOnInit中的服务按预期工作。我打开侧边菜单,导航到另一个页面,然后再次导航到结果页面。但这次页面不会呈现结果。而是渲染ng-template。控制台上没有错误,没有。 ngOnInit正在运行,正在显示console.log(' init');但服务电话不是。如果我将服务调用粘贴到构造函数内或函数内部,它也不起作用。我尝试使用和不使用ngZone,没有...

我需要提一下,如果我直接在结果页面上按F5就可以了。 就在我通过this.router.navigate(['/resultados']);导航到它时 比它没有工作。

这是结果组件:

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

        })
    }
}

这是结果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>

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

}

1 个答案:

答案 0 :(得分:1)

在OnDestroy中使用取消订阅有效!谢谢@ 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();
    }
}