【问题标题】:Microsoft.AspNetCore.NodeServices Captures RxJS IntervalObservable During Angular OnInitMicrosoft.AspNetCore.NodeServices 在 Angular OnInit 期间捕获 RxJS IntervalObservable
【发布时间】:2018-03-16 04:04:32
【问题描述】:

我正在尝试使用 IntervalObservable 在 Angular 4 组件的 OnInit 内启动重复的客户端操作。该应用程序使用 ASP.NET Core。

执行可观察订阅。但是,Microsoft.AspNetCore.NodeServices 中的服务器端预呈现似乎正在执行订阅——从不将呈现的页面返回给浏览器。

我在这里做错了什么?以下是重现的步骤。在这个示例中,我只是尝试在浏览器中console.log 发送心跳。

重现步骤

  1. 创建并cd 进入一个新目录。
  2. 运行dotnet new angular
  3. 运行npm install
  4. ClientApp/app/components/home/home.component.ts的内容替换为下面的代码sn-p。
  5. 运行dotnet run 并转到http://localhost:5000
    import { Component, OnInit } from '@angular/core';
    import { IntervalObservable } from "rxjs/observable/IntervalObservable";

    @Component({
        selector: 'home',
        templateUrl: './home.component.html'
    })
    export class HomeComponent implements OnInit {
        ngOnInit(): void {
            IntervalObservable.create(1500).subscribe((iteration:number)=>console.log(iteration));
        }
    }

当请求进来时,调试控制台开始报告iteration,如代码sn-p所示。页面渲染器超时并最终返回错误页面,但IntervalObservable 订阅继续在调试控制台中迭代。

【问题讨论】:

    标签: angular typescript asp.net-core rxjs


    【解决方案1】:

    我使用https://stackoverflow.com/a/46893433/402726 中显示的技术找到了解决方案。

    本质上,我们使用 Angular 提供的 platform 函数来确定我们是否在浏览器中执行,如果是,则运行浏览器内的心跳。

    以下是问题 sn-p 实施修复的更新形式。

    import { PLATFORM_ID, Component, Inject, OnInit } from "@angular/core";
    import { isPlatformBrowser } from "@angular/common";
    import { IntervalObservable } from "rxjs/observable/IntervalObservable";
    
    @Component({
        selector: "home",
        templateUrl: "./home.component.html"
    })
    export class HomeComponent implements OnInit {
        private isRunningInBrowser: boolean;
        constructor( @Inject(PLATFORM_ID) platformId: string) {
            this.isRunningInBrowser = isPlatformBrowser(platformId);
        }
        public ngOnInit(): void {
            if (!this.isRunningInBrowser) return;
            IntervalObservable.create(1000).subscribe(() => console.log("on an interval"));
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-12-06
      相关资源
      最近更新 更多