2017-12-05 7 views
2

経路変更後にデータがなくなった。経路変更後にデータがなくなった

シナリオ:

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

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

} 

MODEL:comments.ts

export interface Comment { 
    name: string; 
    comment: string; 
} 

[SOLVED]

ここで方法は次のとおりです。それは私には思える

constructor(public afs: AngularFirestore) { 
    } 

    getComments() { 
    this.commentsCollection = this.afs.collection('comments'); 
    return this.comments = this.commentsCollection.valueChanges(); 
    } 
+0

あなたがルートを変更するとデータがなくなったということは、実際には何を意味していませんか。ルートを変更すると、コンポーネントが破棄されるため、コンポーネントの状態に設定されているデータはなくなります。まったく別のルートに切り替えるのですか、またはコメントコンポーネントがまだレンダリングされていますか?あるいは、別のルートに行き、次にコメントコンポーネントに戻ってくることを意味しますか? –

+0

@HugoNoroはい、別のルートに戻ってからもう一度やり直して、コンポーネントをコメントしてください。 データが前に表示された後、別のルートに戻って、再びコメントルートに戻り、データはなくなりました。 –

+0

ありがとう、あなたは私の救い主です。 –

答えて

1

問題:comment.service.ts

、から何かの操作を行います。これに

constructor(public afs: AngularFirestore) { 
    this.commentsCollection = this.afs.collection('comments'); 
    this.comments = this.commentsCollection.valueChanges(); 
    } 

    getComments() { 
    return this.comments; 
    } 

を最初にサービスコンストラクタのコメントを設定していますかそれは一度だけ起こることを意味します。これはhttp呼び出しである可能性が高いので、observableは返された直後に完了します。経路を変更してナビゲートした後のコンポーネントでは、観測可能なものを再起動しないため、サブスクリプションは決して値を受け取りません。観察可能なものはすでに完成しています。

私はあなたがgetComments()メソッドにコンストラクタ内にあるコードを移動すると、問題を解決するはずだと思います。

+0

私にお試しください。とにかくありがとう。 –

+0

GODDAMNITあなたは私の問題を解決します! –

+0

常に喜んで:)。最も重要なことは、あなたはなぜそれを理解しましたか? –

関連する問題