Angular2에서 Http 호출을 연결하는 방법은 무엇입니까?
Angular2 및 Http Observable을 처음 사용합니다. Http 서비스를 호출하고 Observable을 반환하는 구성 요소가 있습니다. Observable을 구독하고 잘 작동합니다.
이제 해당 구성 요소에서 첫 번째 Http 서비스를 호출 한 후 호출이 성공하면 다른 Http 서비스를 호출하고 해당 Observable을 반환합니다. 따라서 첫 번째 호출이 성공하지 못하면 구성 요소는 해당 Observable을 반환하고 반대로 두 번째 호출의 Observable을 반환합니다.
그래서 질문은 Http 호출을 연결하는 가장 좋은 방법은 무엇입니까? 예를 들어 모나드와 같은 우아한 방법이 있습니까?
mergeMap
연산자를 사용하여이를 수행 할 수 있습니다 .
Angular HttpClientModule
4.3+ (사용 ) 및 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);
Angular <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를 사용하여 작업을 수행하는 것은 꽤 좋은 솔루션입니다. 읽기 쉬운가요? 모르겠어요.
이것을 수행하고 더 읽기 쉬운 (내 의견으로는) 다른 방법은 await / async 를 사용하는 것 입니다.
예 :
async getContrat(){
//get the customer
const customer = await this.http.get('./customer.json').toPromise();
//get the contract from 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
}
Promise를 연결할 수도 있습니다. 이 예에 따라
<html>
<head>
<meta charset="UTF-8">
<title>Chaining Promises</title>
</head>
<body>
<script>
const posts = [
{ title: 'I love JavaScript', author: 'Wes Bos', id: 1 },
{ title: 'CSS!', author: 'Chris Coyier', id: 2 },
{ title: 'Dev tools tricks', author: 'Addy Osmani', id: 3 },
];
const authors = [
{ name: 'Wes Bos', twitter: '@wesbos', bio: 'Canadian Developer' },
{ name: 'Chris Coyier', twitter: '@chriscoyier', bio: 'CSS Tricks and Codepen' },
{ name: 'Addy Osmani', twitter: '@addyosmani', bio: 'Googler'},
];
function getPostById(id) {
// create a new promise
return new Promise((resolve, reject) => {
// using a settimeout to mimic a database/HTTP request
setTimeout(() => {
// find the post we want
const post = posts.find(post => post.id == id);
if (post) {
resolve(post) // send the post back
} else {
reject(Error('No Post Was Found!'));
}
},200);
});
}
function hydrateAuthor(post) {
// create a new promise
return new Promise((resolve, reject) => {
// using a settimeout to mimic a database/http request
setTimeout(() => {
// find the author
const authorDetails = authors.find(person => person.name === post.author);
if (authorDetails) {
// "hydrate" the post object with the author object
post.author = authorDetails;
resolve(post);
} else {
reject(Error('Can not find the author'));
}
},200);
});
}
getPostById(4)
.then(post => {
return hydrateAuthor(post);
})
.then(post => {
console.log(post);
})
.catch(err => {
console.error(err);
});
</script>
</body>
</html>
참조 URL : https://stackoverflow.com/questions/34104638/how-to-chain-http-calls-in-angular2
'Development Tip' 카테고리의 다른 글
Dockerfile을 사용하여 호스트에서 컨테이너로 파일을 복사하는 방법 (0) | 2021.01.07 |
---|---|
프로그레시브 렌더링이란 무엇입니까? (0) | 2021.01.07 |
LAMP의 XAMPP 및 WAMP, 무엇이 최고입니까? (0) | 2021.01.07 |
iOS에서 대화 / 전화 통화를 녹음하려면 어떻게해야합니까? (0) | 2021.01.07 |
클래스 "B"가 아닌 클래스 "A"가있는 div를 어떻게 선택합니까? (0) | 2021.01.07 |