我的目标是在服务器中渲染数据。
预期结果:服务器渲染出数据。
实际结果:客户端渲染数据。
图案
Component -> call Use Case -> call Data Source
组件
@Component({
selector: 'app-experience',
templateUrl: './experience.component.html',
styleUrls: ['./experience.component.scss']
})
export class ExperienceComponent implements OnInit {
isBrowser: boolean;
slug: string | null;
experience!: ExperienceEntity | null;
subscriptions: Subscription = new Subscription();
constructor(
@Inject(PLATFORM_ID) platformID: string,
private route: ActivatedRoute,
private getExperienceBySlugUseCase: GetExperienceBySlugUseCase,
) {
this.isBrowser = isPlatformBrowser(platformID);
this.slug = this.route.snapshot.paramMap.get('experience');
this.getExperienceBySlug();
}
ngOnInit(): void {
}
getExperienceBySlug() {
if (this.slug == null) { return }
let subscription = this.getExperienceBySlugUseCase
.get(this.slug)
.subscribe(value => this.experience = value)
this.subscriptions.add(subscription)
}
ngOnDestroy(): void {
this.subscriptions.unsubscribe();
}
}
用例
@Injectable()
export class GetExperienceBySlugUseCase {
constructor(private getExperienceBySlugDataSource: GetExperienceBySlugDataSource) { }
get(slug: string): Observable<ExperienceEntity | null> {
const aObservable = this.getExperienceBySlugDataSource.get(slug);
return aObservable.pipe(
map(val => {
if (val.length == 0) { return null }
return {
title: val[0]['experienceTitle'],
type: val[0]['experienceType'],
category: val[0]['experienceCategory'],
location: {
city: val[0]['location']['city'],
country: val[0]['location']['country'],
},
coverPhoto: {
url: val[0]['coverPhoto']
}
} as ExperienceEntity
})
)
}
}
数据来源
@Injectable()
export class GetExperienceBySlugDataSource {
firestore: Firestore = inject(Firestore);
constructor() { }
get(slug: string) {
const aQuery = query(
collection(this.firestore, "experiences"),
where("slug", "==", slug)
)
return collectionData(aQuery);
}
}