[英]Angular2/4 http.get nested access to “this”
我有這段代碼
let headers = new Headers({ 'Authorization': `${this.user.Token}` });
let options = new RequestOptions({ headers: headers });
this.http.get(environment.apiRoot + 'Customers/Customer/Search/' + term + '/' + value, options)
.map((response) => {
var Data = response.json().Data;
return Data;
}).subscribe(Data => {
this.data.customer.emailAddress = Data.EmailAddress;
this.data.customer.phoneNumber = Data.PhoneNumber;
this.data.customer.firstName = Data.FirstName;
this.data.customer.lastName = Data.LastName;
this.data.customer.streetAddress = Data.StreetAddress;
this.data.customer.city = Data.City;
this.data.customer.state = Data.State;
this.data.customer.zipCode = Data.ZipCode;
this.data.customer.idNumber = Data.IDNumber;
this.data.customer.ID = Data.ID;
this.data.customer.comment = Data.Comment;
// //Check if customer has exsiting orders
this.http.request(environment.apiRoot + 'Orders/Order/Customer/' + Data.ID, options)
.subscribe(odResponse => {
var Data = odResponse.json().Data;
this.data.orders = Data;
this.existingOrders = Data.length > 0;
}, error => {
this.alertService.error('Encountered an error while trying to get customer order data');
});
}, error => {
this.alertService.error('Encountered an error while trying to get customer data');
});
我遇到的問題是,第一個“ GET”完成后,“ this.data.customer”被設置,即使在調試器中,“ this”顯示為“ subscribe”而不是我的組件,第二個“ GET”執行“ this”是訂閱,並說“ this.data.order”未定義,“ this.data”也未定義
所以我想問題是如何在我的訂閱中獲得“ this”作為組件而不是訂閱。
正如Harry所建議的,最好使用switchMap並進行一個訂閱呼叫,而不要進行訂閱中的呼叫。 關於解決方案,請嘗試此
let headers = new Headers({ 'Authorization': `${this.user.Token}` });
let options = new RequestOptions({ headers: headers });
this.http.get(environment.apiRoot + 'Customers/Customer/Search/' + term + '/' + value, options)
.map((response) => { // This extracts the data you require
var Data = response.json().Data;
return Data;
}).switchMap(Data => { // This returns the result of the second observable in
return this.http.request(environment.apiRoot + 'Orders/Order/Customer/' + Data.ID, options)
.map(odResponse => { // We have the response. Extract the json, and return an array with the first element as the old data, and the second element as the new data.
var _Data = odResponse.json().Data;
return [ Data, _Data ];
});
}).subscribe( data => {
let firstSet = data[0];
let secondSet = data[1];
// Now do your assignment
this.data.customer.emailAddress = firstSet.EmailAddress;
this.data.customer.phoneNumber = firstSet.PhoneNumber;
...
...
});
我之所以使用這種方法,是因為您似乎需要第一個調用(ID)返回的數據才能進行第二個調用。 如果不是這種情況,我建議使用Observable.forkJoin。 這是RxJS V4中forkForin的文檔,但仍適用於V5。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.