Подтвердить что ты не робот

Как связать Http звонки в Angular2?

Я новичок в Angular2 и Http Observable. У меня есть компонент, который вызывает службу Http и возвращает Observable. Чем я подписываюсь на этот Наблюдаемый, и он отлично работает.

Теперь я хочу, чтобы в этом компоненте после вызова первой службы Http, если вызов был успешным, вызовите другую службу Http и верните это Observable. Таким образом, если первый вызов не является успешным, компонент возвращает это Observable, напротив он возвращает Observable второго вызова.

Итак, вопрос в том, что лучший способ цепочки Http-вызовов? Есть ли элегантный способ, например, как монады?

4b9b3361

Ответ 1

Вы можете сделать это с помощью оператора 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);

Angular & lt; 4.3 (используя HttpModule) и RxJS & lt; 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 можно найти здесь .

Ответ 2

Использование 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 a possible case
}

Ответ 3

Вы также можете связать обещания. По этому примеру

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