订阅 Observable<number | string>(联合类型)为字符串值提供 NaN

Subscribing on Observable<number | string> (union type) is giving NaN for string values

在一个组件中,我有一个 public 成员定义如下:

public documentId$: Observable<number | string>;

文档ID基本上可以是整数或字符串。在 ngOnInit 我有:

this.documentId$.subscribe(value => {
    // do some stuff with value
    // when value is a string, it is NaN
});

但是,当文档 ID 是字符串时,这不起作用。它只是以 NaN 的形式出现。联合类型的可观察对象不起作用吗?有解决办法吗?

我没有发现使用联合类型有问题。检查你得到的数据。这个有效:https://stackblitz.com/edit/angular-rur73e

import { Component } from '@angular/core';
import { Observable } from 'rxjs';
import { Subject } from 'rxjs';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {

  private subject = new Subject<number | string>();
  public documentId$: Observable<number | string> = this.subject.asObservable();

  ngOnInit() {
  this.documentId$.subscribe(value => {
    // do some stuff with value
    // when value is a string, it is NaN
    console.log(value);
  });
  this.subject.next("abc");
  this.subject.next(3);
  this.subject.next(Date.now());
  }
}

控制台中产生的输出是:

abc
3
1571682486949