我是Angular2的新手,剛開始使用Http請求和observables。 此前我曾與.NET和MySql合作過,現在我正在嘗試學習使用API數據的最佳實踐。結合API請求
我用來連接表,我想找到結合json數據的最佳方法。 在這個例子中,我希望用戶填寫表單並輸入他的電話號碼。
電話號碼的前綴是一個國家代碼和前綴f.ex的下拉列表。德國+49 爲此我需要一個對象:{「德」:」 49」 ,柬埔寨 「855」 ......。}
我做2 HTTP請求到country.io:
http://country.io/phone.json // e.g. DE: 「Germany」
http://country.io/names.json // e.g. DE: 「49」
從這些2請求我使用下面的代碼來創建我的新json對象:myPhonePrefixObject
我認爲代碼太長了,而且它必須可以以更好的方式來完成。
國家service.ts:
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import 'rxjs/Rx';
import { Observable } from 'rxjs/Observable';
@Injectable()
export class CountryService {
constructor( private _http:Http) { }
getCountryCode(): Observable<any> {
return this._http.get('http://crossorigin.me/http://country.io/phone.json')
.map(countryCodes => countryCodes.json());
}
getPhonePrefix(): Observable<any> {
return this._http.get('http://crossorigin.me/http://country.io/names.json')
.map(phonePrefix => phonePrefix.json());
}
}
代碼中userform.component在我導入CountryService
myPhonePrefixObject;
this.countryPhonePrefix()
.then((pp) => {
myPhonePrefixObject = pp;
})
.catch((err) => {
console.log(err);
});
private getCountryCode() {
return new Promise((resolve) => {
this._countryService.getCountryCode()
.subscribe(
res => resolve(res)
);
});
}
private getPhonePrefix() {
return new Promise((resolve, reject) => {
return this._countryService.getPhonePrefix()
.subscribe(
res => resolve(res),
error => reject(error)
);
});
}
private countryPhonePrefix() {
return new Promise((resolve, reject) => {
let cc: Object;
this.getCountryCode()
.then((cCode) => {
cc = cCode;
return this.getPhonePrefix()
})
.then((pPrefix) => {
let pp: Object = {};
Object.keys(cc).forEach((key, index) => {
pp[cc[key]] = pPrefix[key];
});
resolve(pp);
})
.catch((err) => {
reject(err);
});
});
}
嗨哈利 太感謝你了! 這正是我正在尋找的東西,他的回答幫了我很多! –