亚洲在线久爱草,狠狠天天香蕉网,天天搞日日干久草,伊人亚洲日本欧美

為了賬號安全,請及時綁定郵箱和手機立即綁定
已解決430363個問題,去搜搜看,總會有你想問的

如何在Angular2中鏈接Http調用?

如何在Angular2中鏈接Http調用?

胡子哥哥 2019-08-19 14:20:04
如何在Angular2中鏈接Http調用?我是Angular2和Http Observable的新手。我有一個調用Http服務并返回Observable的組件。比我訂閱Observable,它工作正?!,F在,我希望在該組件中,在調用第一個Http服務之后,如果調用成功,則調用其他Http服務并返回該Observable。因此,如果第一次調用不成功,則組件返回Observable,而它返回Observable的第二次調用。所以,問題是,鏈接Http調用的最佳方法是什么?有沒有優雅的方式,比如monads?
查看完整描述

3 回答

?
海綿寶寶撒

TA貢獻1809條經驗 獲得超8個贊

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

}


查看完整回答
反對 回復 2019-08-19
  • 3 回答
  • 0 關注
  • 769 瀏覽

添加回答

舉報

0/150
提交
取消
微信客服

購課補貼
聯系客服咨詢優惠詳情

幫助反饋 APP下載

慕課網APP
您的移動學習伙伴

公眾號

掃描二維碼
關注慕課網微信公眾號