向下滚动到粗体部分以获得答案,
阅读所有内容以了解正在发生的事情。
关于正在发生的事情的一个非常简单的解释:
1.) 用户访问您的应用程序(或刷新)
2.) 服务端在服务端构建html
3.) 它被发送到用户看到它的浏览器
4.) Angular 应用程序“重新创建”应用程序(就好像它是一个常规的非通用应用程序一样)
5.) 发生这种变化时,用户会看到一个闪光。
// You can see this by adding:
// You should see a console log in the server
// `Running on the server with appId=my-app-id`
// and then you'll see in the browser console something like
// `Running on the browser with appId=my-app-id`
export class AppModule {
constructor(
@Inject(PLATFORM_ID) private platformId: Object,
@Inject(APP_ID) private appId: string) {
const platform = isPlatformBrowser(this.platformId) ?
'in the browser' : 'on the server';
console.log(`Running ${platform} with appId=${this.appId}`);
}
}
这是故意的,因为您希望机器人能够获取元标记等。
为了移除闪存,您可以将状态从服务器传输到客户端:
您需要将此添加到 AppServerModule 中的导入中
ServerTransferStateModule
您需要将其添加到您的 AppModule:
BrowserTransferStateModule
在引导浏览器应用程序之前更新 main.ts 文件以侦听 DOMContentLoaded:
document.addEventListener('DOMContentLoaded', () => {
platformBrowserDynamic().bootstrapModule(AppModule)
})
然后是关于如何转移状态的示例:
import { tap, startWith } from 'rxjs/operators';
import { TransferState, makeStateKey } from '@angular/platform-browser';
const ANIMAL_KEY = makeStateKey<any>('animal');
// omitted ...
ngOnInit() {
const id = this.route.snapshot.paramMap.get('name').toLowerCase();
this.animal$ = this.ssrFirestoreDoc(`animals/${id}`);
}
ssrFirestoreDoc(path: string) {
const exists = this.state.get(ANIMAL_KEY, {} as any);
return this.afs.doc<any>(path).valueChanges().pipe(
tap(animal => {
this.state.set(ANIMAL_KEY, animal)
this.seo.generateTags({
title: animal.name,
description: animal.bio,
image: animal.imgURL
});
}),
startWith(exists))
}
我从以下渠道获得所有这些信息:
Angular Universal with Firebase
和
Code and a more thorough explanation