首页 > 解决方案 > 角度 - 无法使用角度通用运行 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();
}

我在universalmodel中发现,假设页面上是轮播效果B,可以通过页面上的链接成功进入B页面A,但是直接打开B页面会失败。

我试图启动旋转木马,ngAfterContentInit()但它不起作用。

标签: angularrxjs

解决方案


如果使用 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
    }
}

推荐阅读