【发布时间】:2020-03-08 10:23:27
【问题描述】:
import { Component } from "@angular/core";
import { Observable, of, throwError, Subscription, forkJoin } from "rxjs";
import { mergeMap, map, delay, timeout, first, take } from "rxjs/operators";
import { ajax } from "rxjs/ajax";
class Test {
id: number;
firstObj: FirstObj;
secondObj: SecondObj;
thirdObj: string;
}
interface FirstObj {
firstObs: boolean;
result: string;
}
interface SecondObj {
secondObs1: boolean;
secondObs2: boolean;
}
@Component({
selector: "my-app",
templateUrl: "./app.component.html",
styleUrls: ["./app.component.css"]
})
export class AppComponent {
private workOrderSubscription: Subscription;
name = "Angular";
obsOne: Observable<any> = of("First Obs")
.pipe(delay(6000))
.pipe(
map(res => {
return {
firstObs: true,
result: res
};
})
);
dataTwo: SecondObj = { secondObs1: true, secondObs2: false };
obsTwo: Observable<any> = of(this.dataTwo);
obsThree: Observable<any> = of("error");
private getId(): Observable<any> {
return of("id" as string);
}
public retrieveWork(): Observable<Test> {
const test: Test = new Test();
this.getId().subscribe((id: number) => {
test.id = id as number;
forkJoin(this.obsOne, this.obsTwo, this.obsThree).subscribe(
([first, second, third]: [FirstObj, SecondObj, string]) => {
// some appropriate checks here
test.firstObj = first as FirstObj;
test.secondObj = second as SecondObj;
test.thirdObj = third as string;
console.log("first is " + first.result);
console.log("second is " + second.secondObs1);
console.log("third is " + third);
console.log(`inside ******************** ${JSON.stringify(test)}`);
return of(test);
},
error => {
//error here
console.log("GOT ERROR");
}
);
});
console.log(`returning ******************** ${JSON.stringify(test)}`);
return of(test);
}
ngOnInit() {
console.log("data ************************");
this.retrieveWork()
.pipe(timeout(10000))
.subscribe(data => {
{
console.log("printing data ***************************");
console.log(`${JSON.stringify(data)}`);
}
});
}
ngOnDestroy() {}
}
我尝试了很多方法,基本上我正在尝试做的是在ngOnInit我订阅get(),但是我得到的数据并不完整。订阅不会等到forkJoin 完全返回。我不确定如何获得完整的数据。
在第一个订阅完成后它发出,我希望第一个和第二个订阅都完成,然后填写“测试”类,然后我的订阅者在ngOnInit 中获取数据。
我的输出是这样的
数据************************
返回 ******************** {"id":"id"}
打印数据***************************
{"id":"id"}
首先是第一个观察点
秒是真的
第三个是错误
内部 ******************** {"id":"id","firstObj":{"firstObs":true,"result":"First Obs"},"secondObj":{"secondObs1":true,"secondObs2":false},"thirdObj":"error"}
正如我们在上面的输出中看到的,只有 id 被打印(在第一次订阅之后),
但是在第二次订阅后,ngOnInit 中的订阅者不再获取数据。
谢谢。
【问题讨论】:
标签: typescript rxjs