![](/img/trans.png)
[英]Ionic 3 - How do I pass id parameter into “http delete” function and delete specific user only?
[英]Ionic 2 - How do I pass id parameter into “http get” function so that it only display data of specific user and not all
我正在嘗試從數據庫服務器加載數據。 我有一個快速的問題:如何將特定的用戶ID傳遞到http get請求中,以便它僅獲取該用戶的數據,而不是整個數據。 我正在使用mongodb作為數據庫,並使用Ionic 2作為前端。
下面是我的代碼:
Home.html中
<ion-card *ngFor="let item of items" (click)="goToOtherPage(item._id)" class="container"> <ion-list> <ion-item> <ion-avatar item-left> <!--<img [src]="item.image" />--> </ion-avatar> <h2 [innerHTML]="item.patient.name"></h2> </ion-item> </ion-list> </ion-card>
Home.ts
load() { let params = { userId: '123' }; this.tunzaProvider.load() .then(data => { this.items = data; }); }
Provider.ts
load() { return new Promise(resolve => { this.http.get(this.apiUrl + 'getusertunzas') .map(res => res.json()) .subscribe(data => { this.data = data; resolve(this.data); }); }); }
這是我通過ID獲得的一種服務方法的示例:
getProduct(id: number): Observable<IProduct> {
if (id === 0) {
return Observable.of(this.initializeProduct());
};
const url = `${this.baseUrl}/${id}`;
return this.http.get(url)
.map(this.extractData)
.do(data => console.log('getProduct: ' + JSON.stringify(data)))
.catch(this.handleError);
}
希望您可以將其應用於您的示例。
此代碼的關鍵部分是網址。 請注意,Id作為參數傳遞給URL。
Home.ts
load(id: number) {
let params = {
userId: id
};
this.tunzaProvider.load(param)
.subscribe(data => {
this.items = data;
}, err => {
console.error(err);
});
}
provider.ts
http get方法:
load(param) {
let headers = new Headers({
'Content-Type': 'application/x-www-form-urlencoded'
});
return this.http.get(`${baseURL}/getusertunzas/${param.userId}`, {
headers: headers
})
.map((response: Response) => {
return response.json();
})
.catch(this.handleError);
}
http發布方法:
load(param) {
let headers = new Headers({
'Content-Type': 'application/x-www-form-urlencoded'
});
return this.http.post(`${baseURL}/getusertunzas`, JSON.stringify(param), {
headers: headers
})
.map((response: Response) => {
return response.json();
})
.catch(this.handleError);
}
錯誤處理程序(在handleError方法中捕獲每個調用的錯誤):
handleError(error) {
console.error(error);
return Observable.throw(error || 'Server error');
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.