在这个小小的示例应用程序中,任何人都可以向我解释为什么detail.component.ts
在第二次访问路由之前没有获得正确的/任何传递到模板的数据。第一次尝试时,该组件为空白,然后再传递前一条路径中的数据。
我不明白,因为正确的ID已传递给getQuote()
方法,而valueChanges()
确实返回了Observable。
因此,在我看来,每次将新ID从路由器传递给方法时,它都应获取一个新Document。
app.service.ts
import { Injectable } from '@angular/core';
import { AngularFirestore, AngularFirestoreCollection, AngularFirestoreDocument } from '@angular/fire/firestore';
import { Observable } from 'rxjs';
import { Quote } from './quote';
@Injectable({
providedIn: 'root'
})
export class AppService {
quote$: Observable<Quote>;
private quotesCollection: AngularFirestoreCollection<Quote> = this.afs.collection('quotes');
quotes$: Observable<Quote[]> = this.quotesCollection.valueChanges({idField: 'id'});
private quoteDocument: AngularFirestoreDocument<Quote>;
constructor(private afs: AngularFirestore) { }
getQuote(id) {
this.quoteDocument = this.quotesCollection.doc(id);
this.quote$ = this.quoteDocument.valueChanges();
}
save(quote: Quote) {
this.quotesCollection.add(quote).then(r => console.log(r));
}
delete(id: string) {
this.quotesCollection.doc(id).delete().then(r => console.log(r));
}
}
list.component.ts
import { ChangeDetectionStrategy, Component } from '@angular/core';
import { AppService } from '../app.service';
@Component({
selector: 'app-list',
templateUrl: './list.component.html',
styleUrls: ['./list.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ListComponent {
quotes$ = this.appService.quotes$;
constructor(private appService: AppService) { }
delete(id: string) {
this.appService.delete(id);
}
}
detail.component.ts
import { ChangeDetectionStrategy, Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { AppService } from '../app.service';
@Component({
selector: 'app-detail',
templateUrl: './detail.component.html',
styleUrls: ['./detail.component.css'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class DetailComponent implements OnInit {
quote$ = this.appService.quote$;
constructor(private appService: AppService,
private activatedRoute: ActivatedRoute) { }
ngOnInit() {
const id = this.activatedRoute.snapshot.paramMap.get('id');
this.appService.getQuote(id);
}
}
detail.component.html
<nav>
<a [routerLink]="['/list']" routerLinkActive="active">Back to list</a>
</nav>
<div *ngIf="quote$ | async as quote">
<h1>{{quote.quote}}</h1>
</div>
答案 0 :(得分:2)
您使用怪异的方式访问quote$
。我认为更好:
`
getQuote(id) {
this.quoteDocument = this.quotesCollection.doc(id);
return this.quoteDocument.valueChanges();
}
`
然后在组件上: `
ngOnInit() {
const id = this.activatedRoute.snapshot.paramMap.get('id');
this.quote$ = this.appService.getQuote(id);
}
`
对我来说更清楚了,我认为它可以解决您的问题