我正在尝试订阅 Observable 并从响应中分配一些数据,但不知何故我的代码并没有等待响应。基本上,console.log(this.newIds) 首先运行,并且始终为空,因为订阅不会等待来自后端的响应。如何强制我的代码等待响应到来?
this.repository.getById(Ids).subscribe((response) => {
console.log(response);
this.newIds = response.map((id) => {
return id;
});
});
console.log(this.newIds);
Run Code Online (Sandbox Code Playgroud) 我正在尝试测试这两个异步函数。问题是其中一个函数每 10 秒自动调用一次。我尝试使用tick()或flush(),但仍然遇到相同的错误:1个周期性计时器仍在队列中。我该如何解决?我的代码:
ngOnInit(): void {
const dialogRef = this.openProgressDialog();
this.getSubscription = this.getAll();
dialogRef.close();
this.postSubscription = interval(10000).subscribe(() => {
this.sendAll();
this.dataSource.data = this.jobs;
this.table.renderRows();
});
}
Run Code Online (Sandbox Code Playgroud)
考试:
test("test", fakeAsync(() => {
const getSpy = spyOn(otdRepositoryMock, "getAll").and.returnValue(of(jobs));
const getSubscribeSpy = spyOn(otdRepositoryMock.getAll(), "subscribe");
const postSpy = spyOn(otdRepositoryMock, "sendAll").and.returnValue(of(jobs));
const postSubscribeSpy = spyOn(otdRepositoryMock.sendAll([2]), "subscribe");
component.ngOnInit();
//tick();
//flush();
expect(getSpy).toHaveBeenCalled();
expect(getSubscribeSpy).toHaveBeenCalled();
expect(postSpy).toHaveBeenCalled();
expect(postSubscribeSpy).toHaveBeenCalled();
}));
Run Code Online (Sandbox Code Playgroud)