programing

관찰 가능한 캐스팅 결과.각 2에서 각 유형별로 포크조인

prostudy 2022. 3. 17. 00:53
반응형

관찰 가능한 캐스팅 결과.각 2에서 각 유형별로 포크조인

내가 Angle 2에 페이지가 표시되기 전에 서버로부터 2가지 다른 것을 로드해야 하는 컴포넌트가 있다고 하자.나는 그 모든 것들을 끄고 그들이 그 페이지가 Loaded = true라고 다시 말할 때 한 이벤트 핸들러를 불러주길 바란다.내가 이렇게 생긴 서비스 클래스가 있다고 가정해보자.

export class MyService {
   getStronglyTypedData1(): Observable<StrongData1[]>{
      return this.http.get('http://...').map((response:Response) => <StrongData1[]>response.json());
   }
   getStronglyTypedData2(): Observable<StrongData2[]>{
         return this.http.get('http://...').map((response:Response) => <StrongData2[]>response.json());
   }
}

그럼 그 서비스 클래스를 이렇게 사용하는 부품이 있어.

export class MyComponent implements OnInit {
   isLoaded = false;
   stronglyTypedData1: StrongData1[];
   stronglyTypedData2: StrongData2[];

   constructor(private myService:MyService){ }

   ngOnInit(){
      var requests [ 
         this.myService.getStronglyTypedData1(),
         this.myService.getStronglyTypedData2()
      ];
      Observable.forkJoin(requests).subscribe(
         results => {
            this.stronglyTypedData1 = results[0];
            this.stronglyTypedData2 = results[1];
            this.isLoaded = true;
         });
   }
}

TypeScript 컴파일러는 유형 객체를 StrongData1[] 유형으로 변환할 수 없다고 불평하고 있다.StrongData1과 StrongData2를 "임의"로 변경하면 모든 것이 정상적으로 작동한다.타이프스크립트의 강한 오타가 주는 혜택을 잃어가고 있으니 차라리 안 하는 게 낫겠다.

ForkJoin의 결과를 각 유형으로 어떻게 캐스팅하시겠습니까?

내게는 항상 관찰 가능에 직접 요청을 추가할 때 효과가 있다.결과 배열에는 forkJoin을 사용한 다음 es6 소멸을 사용하십시오.

당신의 코드가 이렇게 보일 수 있도록

Observable
    .forkJoin(this.myService.getStronglyTypedData1(), this.myService.getStronglyTypedData2())
    .subscribe(
        ([typeData1, typeData2]) => {
            this.stronglyTypedData1 = typeData1;
            this.stronglyTypedData2 = typeData2;
            this.isLoaded = true;
        }
    );

해보다

(results:[StrongData1[], StrongData2[]]) =>

Typescript에서 함수 매개변수(이 경우 튜플):

const requests = [ 
    this.myService.getStronglyTypedData1(),
    this.myService.getStronglyTypedData2()
];
forkJoin(requests)
    .subscribe(([data1, data2]: [StrongData1[], StrongData2[]]) => {
        this.stronglyTypedData1 = data1;
        this.stronglyTypedData2 = data2;
        this.isLoaded = true;
    });

참조URL: https://stackoverflow.com/questions/45306324/casting-results-from-observable-forkjoin-to-their-respective-types-in-angular-2

반응형