1

我正在尝试编写一个服务来衡量应用程序变得稳定的完成时间。这是服务:

测量服务.ts

import { ApplicationRef, Injectable } from "@angular/core";
import { first, map } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class MeasureService {
  public constructor(private readonly applicationRef: ApplicationRef) { }

  public measure(): void {
    const startTime = Date.now();

    console.log(startTime);
    /**
     * Test stability metrics of application.
     */
    this.applicationRef.isStable.pipe(
      first(isStable => isStable),
      map(() => {
        /* tslint:disable-next-line:no-console */
        console.log("App stable ("+ Math.round((Date.now() - startTime) / 1000) + " secs)");
      })
    );
  }
}

app.module.ts(缩写):

...
@NgModule({
   providers: [
      MeasureService
   ]
})

根组件.ts

import { Component, OnInit } from "@angular/core";
import { MeasureService } from "../application-insights/measure.service";

@Component({
  selector: "mr-root",
  template: `
    <router-outlet></router-outlet>
  `,
})
export class RootComponent implements OnInit {
  public constructor(
    private readonly measureService: MeasureService
  ) {  
    this.measureService.measure();    
  }

  public ngOnInit(): void {
  }
}

第一个console.log正确MeasureService记录时间。但是,似乎applicationRef.isStable永远不会触发,因此第二个console.log永远不会写入控制台。

我这样做对吗,还是我错过了什么?

4

1 回答 1

1

measure.service.ts(更新):

import { ApplicationRef, Injectable } from "@angular/core";
import { first } from 'rxjs/operators';

@Injectable({
  providedIn: 'root'
})
export class MeasureService {
  public constructor(private readonly applicationRef: ApplicationRef) { }

  public measure(): void {
    const startTime = Date.now();

    /**
     * Test stability metrics of application.
     */
    this.applicationRef.isStable.pipe(
      first(isStable => isStable)
    ).subscribe(() => {
      /* tslint:disable-next-line:no-console */
      console.log("App stable ("+ Math.round((Date.now() - startTime) / 1000) + " secs)");
    });
  }
}
于 2019-11-13T20:21:54.387 回答