我已经使用模块联合将一个应用程序迁移到 MFE 架构,并且在运行时抛出了看起来很神秘的错误:
You provided an invalid object where a stream was expected error. You can provide an Observable, Promise, Array, or Iterable
.
导致它的代码如下所示:
this
.getSomeObservable()
.pipe(
switchMap(() => this.getOtherObservable()) // switching here causes the error
).subscribe()
但是我很确定代码没问题...
在分析堆栈跟踪时,错误源自:
https://github.com/ReactiveX/rxjs/blob/6.6.7/src/internal/util/subscribeTo.ts
export const subscribeTo = <T>(result: ObservableInput<T>): (subscriber: Subscriber<T>) => Subscription | void => {
if (!!result && typeof result[Symbol_observable] === 'function') {
return subscribeToObservable(result as any);
} else if (isArrayLike(result)) {
return subscribeToArray(result);
} else if (isPromise(result)) {
return subscribeToPromise(result as Promise<any>);
} else if (!!result && typeof result[Symbol_iterator] === 'function') {
return subscribeToIterable(result as any);
} else {
const value = isObject(result) ? 'an invalid object' : `'${result}'`;
const msg = `You provided ${value} where a stream was expected.`
+ ' You can provide an Observable, Promise, Array, or Iterable.';
throw new TypeError(msg);
}
};
在我的情况下,result
是类型BehaviorSubject
。
但是,当我比较应用程序在非联合和联合中运行时的堆栈跟踪时,问题就在这里:
https://github.com/ReactiveX/rxjs/blob/6.6.7/src/internal/innerSubscribe.ts#L110
if (result instanceof Observable) {
return result.subscribe(innerSubscriber);
}
没有模块联合,这if
是真的,当我查看原型时,我可以更深入地找到Observable
.
然而在联邦环境中,这个表达式是错误的。
重构为:
this
.getSomeObservable()
.subscribe(() => this.getOtherObservable().subscribe())
不再抛出错误。
您对如何正确修复它有任何想法吗?