sourcecode

Angular 2에서 HTTP 통화를 체인화하려면 어떻게 해야 합니까?

codebag 2023. 8. 26. 11:21
반응형

Angular 2에서 HTTP 통화를 체인화하려면 어떻게 해야 합니까?

Angular 2와 HTTP Observables는 처음입니다.HTTP 서비스를 호출하고 관찰 가능 항목을 반환하는 구성 요소가 있습니다.그러면 저는 그 관찰 가능한 것을 구독하고 그것은 잘 작동합니다.

이 구성 요소에서 첫 번째 HTTP 서비스를 호출한 후, 호출이 성공적이면 다른 HTTP 서비스를 호출하여 관찰 가능한 항목을 반환합니다.따라서 첫 번째 호출이 성공하지 못하면 구성 요소는 해당 관찰 가능을 반환하고 반대로 두 번째 호출의 관찰 가능을 반환합니다.

HTTP 통화를 연결하는 가장 좋은 방법은 무엇입니까?예를 들어 모나드와 같은 우아한 방법이 있습니까?

다음을 사용하여 이 작업을 수행할 수 있습니다.mergeMap교환입니다.

Angular 4.3+(사용)HttpClientModule) 및 RxJS 6+

import { mergeMap } from 'rxjs/operators';

this.http.get('./customer.json').pipe(
  mergeMap(customer => this.http.get(customer.contractUrl))
).subscribe(res => this.contract = res);

각도 < 4.3 (사용)HttpModule) 및 RxJS < 5.5

연산자 가져오기map그리고.mergeMap그러면 다음과 같이 두 개의 통화를 연결할 수 있습니다.

import 'rxjs/add/operator/map'; 
import 'rxjs/add/operator/mergeMap';

this.http.get('./customer.json')
  .map((res: Response) => res.json())
  .mergeMap(customer => this.http.get(customer.contractUrl))
  .map((res: Response) => res.json())
  .subscribe(res => this.contract = res);

자세한 내용은 http://www.syntaxsuccess.com/viewarticle/angular-2.0-and-http 를 참조하십시오.

mergeMap 연산자에 대한 자세한 내용은 여기에서 확인할 수 있습니다.

rxjs를 사용하여 작업을 수행하는 것은 꽤 좋은 해결책입니다.읽기 쉽습니까?몰라.

이 작업을 수행하고 더 읽기 쉬운 다른 방법은 wait/async를 사용하는 것입니다.

예:

async getContrat(){
    // Get the customer
    const customer = await this.http.get('./customer.json').toPromise();

    // Get the contract from the URL
    const contract = await this.http.get(customer.contractUrl).toPromise();

    return contract; // You can return what you want here
}

그럼 부르세요 :)

this.myService.getContrat().then( (contract) => {
  // do what you want
});

또는 비동기 함수의 경우:

const contract = await this.myService.getContrat();

try/catch를 사용하여 오류를 관리할 수도 있습니다.

let customer;
try {
  customer = await this.http.get('./customer.json').toPromise();
}catch(err){
   console.log('Something went wrong will trying to get customer');
   throw err; // Propagate the error
   //customer = {};  // It's a possible case
}

언급URL : https://stackoverflow.com/questions/34104638/how-can-i-chain-http-calls-in-angular-2

반응형