我的数据在更改路线后消失了。
情景:
CommentComponent(显示数据) - > ChangeRoute - > CommentComponent(未显示数据)
数据仅在第一次加载时显示,但每当我更改路径时它就会消失。
我发现这个问题与我的案例/问题类似: No data for FireStore after use of routerlink
但是没有一条评论/回答是有帮助的。所以我决定提出这个问题。
COMPONENT.HTML:comment.component.html
:
<ng-template #noComments>
<h1>No comment yet.</h1>
</ng-template>
<div *ngIf="comments?.length > 0; else noComments">
<h1 style="margin-bottom: 3.5vh;">Comments</h1>
<ul *ngFor="let comment of comments">
<li>
<mat-card>
<h3>{{comment.name}}</h3>
<p>{{comment.comment}}</p>
</mat-card>
</li>
</ul>
</div>
COMPONENT.TypeScript:comment.component.ts
:
import { Component, OnInit } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';
import { CommentService } from '../services/comment.service';
import { Comment } from '../models/comment';
@Component({
selector: 'app-comment',
templateUrl: './comment.component.html',
styleUrls: ['./comment.component.css']
})
export class CommentComponent implements OnInit {
comments: Comment[];
constructor(private commentService: CommentService) {
}
ngOnInit() {
this.commentService.getComments().subscribe(comments => {
this.comments = comments;
});
}
}
服务:comments.service.ts
:
import { Injectable } from '@angular/core';
import { Comment } from '../models/comment';
import { Observable } from 'rxjs/observable';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from 'angularfire2/firestore';
@Injectable()
export class CommentService {
commentsCollection: AngularFirestoreCollection<Comment>;
comments: Observable<Comment[]>;
constructor(public afs: AngularFirestore) {
this.commentsCollection = this.afs.collection('comments');
this.comments = this.commentsCollection.valueChanges();
}
getComments() {
return this.comments;
}
}
模特:comments.ts
:
export interface Comment {
name: string;
comment: string;
}
[解决]
以下是:
在comment.service.ts
中,请执行以下操作:
constructor(public afs: AngularFirestore) {
this.commentsCollection = this.afs.collection('comments');
this.comments = this.commentsCollection.valueChanges();
}
getComments() {
return this.comments;
}
对此:
constructor(public afs: AngularFirestore) {
}
getComments() {
this.commentsCollection = this.afs.collection('comments');
return this.comments = this.commentsCollection.valueChanges();
}
答案 0 :(得分:5)
在我看来,问题是你最初是在服务构造函数上设置注释,这意味着它只会发生一次。由于这很可能是一个http调用,因此observable将在返回后立即完成。在更改路由并再次导航到组件后的组件中,不会重新启动可观察的só,订阅将永远不会收到任何值。观察已经完成了。
我相信如果你将构造函数中的代码移动到getComments()方法,它应该解决你的问题。