angular - 角度 - 无法使用角度通用运行 rxjs 间隔
问题描述
我通过RXJS的间隔时间改变参数做了一个轮播效果。
我发现它在开发模式下工作(ng serve),但在universal
模式下它不能正常工作,它无法进入页面。
例如:
n: number = 0;
max: number = 5;
constructor(){}
ngOnInit() {
this.carousel();
}
carousel() {
this.subscription = interval(2000).subscribe(() => {
//In universal, the console.log message show in node.js background log message not in browser console message. Each time the page is reorganized, it will be executed once and cannot be destroyed.
console.log(`show the photo: ${this.n}`);
if (this.n>this.max){
this.n = 0;
}else{
this.n = this.n+1;
}
}
}
ngOnDestroy() {
this.subscription.unsubscribe();
}
我在universal
model中发现,假设页面上是轮播效果B
,可以通过页面上的链接成功进入B页面A
,但是直接打开B页面会失败。
我试图启动旋转木马,ngAfterContentInit()
但它不起作用。
解决方案
如果使用 Angular Universal,则需要使用isPlatformBrowser
来排除只能在前端运行的代码。
示例:
import { isPlatformBrowser } from '@angular/common';
import { PLATFORM_ID } from "@angular/core";
constructor(
@Inject(PLATFORM_ID) private platformId: Object
) { }
do(){
if (isPlatformBrowser(this.platformId)) {
//do something, only runs on the front end
}
}
推荐阅读
- java - 检查图像尺寸
- ruby-on-rails - Rails:在表单上使用 reCaptcha,用于传入参数的模型
- python - Pyomo:将结果保存到 CSV 文件
- java - 使用 Collections.unmodifiableMap 和 ConcurrentHashMap / HashMap 作为参数
- python - 如何定义矩阵的变量(不是数组)?归一化,Min_of_Matrix,Max_
- php - php 7.3 - 类常量作为默认参数值崩溃
- html - 如何确保可折叠表格后面的文本显示在其下方,而不是右侧?
- javascript - 使用 javascript 打开页面时立即显示上传对话框
- python - 我有一个包含文本和计算的 excel 文件,在 python 中读取 excel 文件的最佳方法是什么?
- firebase - 在 Firebase 控制台中创建主题