Fra*_*aya 6 firebase angularfire angular google-cloud-firestore
改变路线后我的数据消失了.
场景:
CommentComponent(显示数据) - > ChangeRoute - > CommentComponent(未显示数据)
数据仅在第一次加载时显示,但每当我更改路径时它就会消失.
我发现这个问题与我的案例/问题类似: 使用routerlink后没有FireStore的数据
但是没有一条评论/答案是有帮助的.所以我决定提出这个问题.
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>
Run Code Online (Sandbox Code Playgroud)
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;
});
}
}
Run Code Online (Sandbox Code Playgroud)
服务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;
}
}
Run Code Online (Sandbox Code Playgroud)
型号comments.ts:
export interface Comment {
name: string;
comment: string;
}
Run Code Online (Sandbox Code Playgroud)
[解决了]
这是如何做:
在comment.service.ts,做一些事情来自:
constructor(public afs: AngularFirestore) {
this.commentsCollection = this.afs.collection('comments');
this.comments = this.commentsCollection.valueChanges();
}
getComments() {
return this.comments;
}
Run Code Online (Sandbox Code Playgroud)
对此:
constructor(public afs: AngularFirestore) {
}
getComments() {
this.commentsCollection = this.afs.collection('comments');
return this.comments = this.commentsCollection.valueChanges();
}
Run Code Online (Sandbox Code Playgroud)
在我看来,问题是你最初是在服务构造函数上设置注释,这意味着它只会发生一次.由于这很可能是一个http调用,因此observable将在返回后立即完成.在更改路由并再次导航到组件后的组件中,不会重新启动可观察的só,订阅将永远不会收到任何值.观察已经完成了.
我相信如果你将构造函数中的代码移动到getComments()方法,它应该解决你的问题.
| 归档时间: |
|
| 查看次数: |
719 次 |
| 最近记录: |