我有一个到目前为止可以正常工作的Angular 2应用程序。我的GlobalsService.getGlobals()通过我的OptionService.getOptions()获取“美国州”。我的代码失败的地方是Karma / Jasmine测试。
在当前测试设置中调用getGlobals()时,出现“ this._subscribe不是函数”错误。我发现调试起来很困难,因为谷歌浏览器无法配合。
我的getGlobals()代码已添加调试。我在getOptions()和.subscribe()之间拆分了代码,以查看发生了什么。
public getGlobals(): void {
let asdf = this.optionService.getOptions();
console.log("asdf is " + (typeof asdf) + ", asdf.subscribe is: " + asdf.subscribe);
try {
asdf.subscribe(
(options: Option[]) => this.fillOptions(options),
(error: string) => this.error = error
);
} catch(error) {
console.log("caught error involving asdf, it is: " + error);
throw error;
}
}
当我运行此代码时,我得到:
LOG: 'asdf is object, asdf.subscribe is: function (observerOrNext, error, complete) {
[1] var operator = this.operator;
[1] var sink = toSubscriber_1.toSubscriber(observerOrNext, error, complete);
[1] if (operator) {
[1] operator.call(sink, this.source);
[1] }
[1] else {
[1] sink.add(this._subscribe(sink));
[1] }
[1] if (sink.syncErrorThrowable) {
[1] sink.syncErrorThrowable = false;
[1] if (sink.syncErrorThrown) {
[1] throw sink.syncErrorValue;
[1] }
[1] }
[1] return sink;
[1] }'
您可以从node_modules / rxjs / Observable.js中看到asdf.subscribe的代码。因此,getOptions()的返回值是一个Observable。它具有许多特性,其中包括:
_subscribe: Array[4] (each item is an Object of my Option data type)
_proto_: Object
_subscribe: (subscriber)
subscribe: (observer or next, error, complete)
但是,如果我继续执行代码,则会收到错误消息。带有asdf变量“ this”的位置是GlobalsService。
我嘲笑的OptionService代码是:
@Injectable()
export class MockOptionService {
constructor() { }
getOptions(): Observable<Option[]> {
let options: Option[] = [
{ id: 'IN', name: 'Indiana', topic: Option.TOPIC_STATE },
{ id: 'NJ', name: 'New Jersey', topic: Option.TOPIC_STATE },
{ id: 'CONCERT', name: "Concert", topic: Option.TOPIC_EVENT_TYPE },
{ id: 'NY', name: 'New York', topic: Option.TOPIC_STATE }
];
return Observable.create(options);
}
}
这是通过以下方式注入的:
describe('Globals Service', () => {
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
{ provide: OptionService, useClass: MockOptionService },
{ provide: GlobalsService, useClass: GlobalsService }
]
});
[SNIP]
});
就像我说的那样,调试此工具时遇到了Chrome的问题。如果我在调试器中显示Observable.js源并尝试设置断点,浏览器将为不存在的Observable.ts文件显示空白页。断点在任何地方都不会显示。该代码在不存在的Observable.ts:92上停止。
我的问题是:
1.我可以说服Chrome在Typescript世界中给我一个Java断点吗?
2.创建对象数组然后将其附加到Observable的适当功能是什么?我怀疑Observable.create()是错误的。
谢谢杰罗姆。
使用Observable.of
代替。Observable.create
需要订阅功能。Observable.create
是用来创建“ custom-logic”的Observable
,而Observable.of
只是创建了一个基础Observable
,该基础发出了传递给它的值。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句