Typescript forkJoin并不是在等待所有的可观察对象完成 从“@angular/core”导入{Component}”; 从“rxjs”导入{Observable、of、throwerr、Subscription、forkJoin}; 从“rxjs/operators”导入{mergeMap,map,delay,timeout,first,take}; 从“rxjs/ajax”导入{ajax}; 课堂测试{ id:编号; firstObj:firstObj; secondObj:secondObj; thirdObj:字符串; } 接口第一对象{ firstObs:布尔型; 结果:字符串; } 接口二次对象{ 第二类:布尔型; 第二类:布尔型; } @组成部分({ 选择器:“我的应用程序”, templateUrl:“./app.component.html”, 样式URL:[“/app.component.css”] }) 导出类AppComponent{ 私人工单订阅:订阅; name=“Angular”; obsOne:Observable=of(“第一个Obs”) .管道(延迟(6000)) .烟斗( 地图(res=>{ 返回{ 是的, 结果:res }; }) ); dataTwo:SecondObj={secondObs1:true,secondObs2:false}; obsTwo:Observable=of(this.dataTwo); 观测值三:可观测值=of(“误差”); 私有getId():可观察{ 返回(“id”作为字符串); } 公共检索工作():可观察{ 常量测试:测试=新测试(); this.getId().subscribe((id:number)=>{ test.id=id作为编号; forkJoin(this.obsOne,this.obs2,this.obsThree)。订阅( ([first,second,third]:[FirstObj,SecondObj,string])=>{ //这里有一些适当的检查 test.firstObj=第一个作为firstObj; test.secondObj=第二个作为secondObj; test.thirdObj=第三个as字符串; console.log(“第一个是”+first.result); log(“第二个是”+second.secondObs1); console.log(“第三个是”+third); log(`inside***************${JSON.stringify(test)}`); 返回(测试); }, 错误=>{ //这里出错 log(“得到错误”); } ); }); log(`returning***************${JSON.stringify(test)}`); 返回(测试); } 恩戈尼尼特(){ console.log(“数据*************************”; 这个。retrieveWork() .管道(超时(10000)) .订阅(数据=>{ { console.log(“打印数据*************************”; log(`${JSON.stringify(data)}`); } }); } ngOnDestroy(){} }

Typescript forkJoin并不是在等待所有的可观察对象完成 从“@angular/core”导入{Component}”; 从“rxjs”导入{Observable、of、throwerr、Subscription、forkJoin}; 从“rxjs/operators”导入{mergeMap,map,delay,timeout,first,take}; 从“rxjs/ajax”导入{ajax}; 课堂测试{ id:编号; firstObj:firstObj; secondObj:secondObj; thirdObj:字符串; } 接口第一对象{ firstObs:布尔型; 结果:字符串; } 接口二次对象{ 第二类:布尔型; 第二类:布尔型; } @组成部分({ 选择器:“我的应用程序”, templateUrl:“./app.component.html”, 样式URL:[“/app.component.css”] }) 导出类AppComponent{ 私人工单订阅:订阅; name=“Angular”; obsOne:Observable=of(“第一个Obs”) .管道(延迟(6000)) .烟斗( 地图(res=>{ 返回{ 是的, 结果:res }; }) ); dataTwo:SecondObj={secondObs1:true,secondObs2:false}; obsTwo:Observable=of(this.dataTwo); 观测值三:可观测值=of(“误差”); 私有getId():可观察{ 返回(“id”作为字符串); } 公共检索工作():可观察{ 常量测试:测试=新测试(); this.getId().subscribe((id:number)=>{ test.id=id作为编号; forkJoin(this.obsOne,this.obs2,this.obsThree)。订阅( ([first,second,third]:[FirstObj,SecondObj,string])=>{ //这里有一些适当的检查 test.firstObj=第一个作为firstObj; test.secondObj=第二个作为secondObj; test.thirdObj=第三个as字符串; console.log(“第一个是”+first.result); log(“第二个是”+second.secondObs1); console.log(“第三个是”+third); log(`inside***************${JSON.stringify(test)}`); 返回(测试); }, 错误=>{ //这里出错 log(“得到错误”); } ); }); log(`returning***************${JSON.stringify(test)}`); 返回(测试); } 恩戈尼尼特(){ console.log(“数据*************************”; 这个。retrieveWork() .管道(超时(10000)) .订阅(数据=>{ { console.log(“打印数据*************************”; log(`${JSON.stringify(data)}`); } }); } ngOnDestroy(){} },typescript,rxjs,Typescript,Rxjs,我尝试了很多方法,基本上我想做的是在ngOnInit中订阅get(),但是我得到的数据并不完整。订阅不会等待forkJoin完全返回。我不知道怎样才能得到完整的数据 在第一个订阅完成后,我希望第一个和第二个订阅完成并填充“Test”类,然后我的订阅方在ngOnInit中获取数据 我的输出如下所示 资料************************ 返回***************{“id”:“id”} 打印数据*************************** {“id”:“id”} 第

我尝试了很多方法,基本上我想做的是在
ngOnInit
中订阅get(),但是我得到的数据并不完整。订阅不会等待
forkJoin
完全返回。我不知道怎样才能得到完整的数据

在第一个订阅完成后,我希望第一个和第二个订阅完成并填充“Test”类,然后我的订阅方在
ngOnInit
中获取数据

我的输出如下所示

资料************************

返回***************{“id”:“id”}

打印数据***************************

{“id”:“id”}

第一个是第一个Obs

第二个是真的

第三是错误

在***************{“id”:“id”,“firstObj”:{“firstObs”:true,“result”:“First Obs”},“secondObj”:{“secondObs1”:true,“secondObs2”:false},“thirdObj”:“error”}

正如我们在上面的输出中所看到的,仅打印id(在第一次订阅之后), 但是在第二次订阅之后,
ngOnInit
中的订户不再获取数据


谢谢。

最后,这似乎奏效了。我是RXJS的新手。欢迎提出任何建议

还处理了所有错误案例


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() {}
}


从“@angular/core”导入{Component};
进口{
可见的,
属于
投手,
订阅
forkJoin,
组合测试
}来自“rxjs”;
进口{
合并地图,
地图,
延迟
超时,
第一,
拿
捕捉错误
}来自“rxjs/运营商”;
从“rxjs/ajax”导入{ajax};
课堂测试{
id:编号;
firstObj:firstObj;
secondObj:secondObj;
}
接口第一对象{
firstObs:布尔型;
结果:字符串;
}
接口二次对象{
第二类:布尔型;
第二类:布尔型;
}
@组成部分({
选择器:“我的应用程序”,
templateUrl:“./app.component.html”,
样式URL:[“/app.component.css”]
})
导出类AppComponent{
私人工单订阅:订阅;
name=“Angular”;
dataone:FirstObj={firstObs:true,结果:“hai”};
obsOne:Observable=of(this.dataone).pipe(延迟(1000));
dataTwo:SecondObj={secondObs1:true,secondObs2:false};
obsTwo:Observable=throwerr(this.dataTwo);
私有getId():可观察{
归还(1)条管道(延迟(4000));
}
public get():可观察{
让测试:测试=新测试();
返回新的可观察对象(订户=>
this.getId().pipe(超时(5000)).subscribe(
(身份证号码)=>{
test.id=id;
分叉连接(
this.obsOne.pipe(超时(1000)).pipe(catchError(error=>of(null)),
this.obstow.pipe(超时(1000)).pipe(catchError(error=>of(null)),
).订阅(([第一,第二])=>{
test.firstObj=第一个;
test.secondObj=秒;
console.log(“打印数据***************************************2”);
log(`${JSON.stringify(test)}`);
下一步(测试);
subscriber.complete();
});
},
错误=>{
log(“获取数据时出错”);
subscriber.error(“获取数据时出错”);
subscriber.unsubscribe();
}
)
);
}
恩戈尼尼特(){
let subscription:subscription=this.get()
.管道(超时(6000))
.订阅(
(数据:测试)=>{
console.log(“登录订阅”);
log(`${JSON.stringify(data)}`);
},
错误=>{
console.log(“错误”+err);
订阅。取消订阅();
}
);
}
ngOnDestroy(){}
}

我用更高的-
import { Component } from "@angular/core";
import {
  Observable,
  of,
  throwError,
  Subscription,
  forkJoin,
  combineLatest
} from "rxjs";
import {
  mergeMap,
  map,
  delay,
  timeout,
  first,
  take,
  catchError
} from "rxjs/operators";
import { ajax } from "rxjs/ajax";

class Test {
  id: number;
  firstObj: FirstObj;
  secondObj: SecondObj;
}

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";

  dataone: FirstObj = { firstObs: true, result: "hai" };
  obsOne: Observable<any> = of(this.dataone).pipe(delay(1000));
  dataTwo: SecondObj = { secondObs1: true, secondObs2: false };
  obsTwo: Observable<any> = throwError(this.dataTwo);

  private getId(): Observable<any> {
    return of(1).pipe(delay(4000));
  }

  public get(): Observable<any> {
    let test: Test = new Test();
    return new Observable(subscriber =>
      this.getId().pipe(timeout(5000)).subscribe(
        (id: number) => {
          test.id = id;
          forkJoin(
            this.obsOne.pipe(timeout(1000)).pipe(catchError(error => of(null))),
            this.obsTwo.pipe(timeout(1000)).pipe(catchError(error => of(null))),
          ).subscribe(([first, second]) => {
            test.firstObj = first;
            test.secondObj = second;
            console.log("printing data ***************************2");
            console.log(`${JSON.stringify(test)}`);
            subscriber.next(test);
            subscriber.complete();
          });
        },
        err => {
          console.log("error while getting data");
          subscriber.error("error while getting data");
          subscriber.unsubscribe();
        }
      )
    );
  }

  ngOnInit() {
    let subscription: Subscription = this.get()
      .pipe(timeout(6000))
      .subscribe(
        (data: Test) => {
          console.log("in subscribe");
          console.log(`${JSON.stringify(data)}`);
        },
        err => {
          console.log("ERROR " + err);
          subscription.unsubscribe();
        }
      );
  }
  ngOnDestroy() {}
}
import { Component } from "@angular/core";
import { Observable, of, forkJoin } from "rxjs";
import { switchMap, map, delay, timeout} from "rxjs/operators";

class Test {
  id: number;
  firstObj: FirstObj;
  secondObj: SecondObj;
  thirdObj: string;
}

interface FirstObj {
  firstObs: boolean;
  result: string;
}

interface SecondObj {
  secondObs1: boolean;
  secondObs2: boolean;
}


@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = "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");


  // Not sure why this was sometimes a string and sometimes a number
  // Changed to a number.
  private getId(): Observable<number> {
    return of(7);
  }

  // Made this declarative so you could do further operations on the
  // stream as needed.
  myTest$ =
    this.getId()
      .pipe(
        // Added switchMap, which is a higher-order mapping operator
        // and automatically subscribes (and unsubscribes) to its inner Observables
        switchMap(id => {
          const test: Test = new Test();
          test.id = id;
          return forkJoin(this.obsOne, this.obsTwo, this.obsThree)
            .pipe(
              map(([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 test;
              })
            )
        })
      );

  ngOnInit() {
    console.log("data ************************");
    this.myTest$
      .pipe(timeout(10000))
      .subscribe(data => {
        {
          console.log("printing data ***************************");
          console.log(`${JSON.stringify(data)}`);
        }
      });
  }

  ngOnDestroy() { }
}