我是离子和打字稿的新手。我有一个api。为了安全起见,我只能使用post方法访问api,并在body中传递参数。我想要使用这些api的json数据。但我不知道在体内传递参数
我附上了我试过的编码
sample.ts
import { Component } from '@angular/core';
import { IonicPage, NavParams } from 'ionic-angular';
import {HttpProvider} from '../../providers/http/http';
import { NavController, LoadingController } from 'ionic-angular';
import { TraineristorePage } from '../traineristore/traineristore';
import { StorePage } from '../store/store';
import 'rxjs/add/operator/map';
import {Http,HttpHeaders} from '@angular/http';
import {RequestOptions, Request, RequestMethod} from '@angular/http';
@IonicPage()
@Component({
selector: 'page-sample',
templateUrl: 'sample.html',
providers:[HttpProvider]
})
export class SamplePage {
users: any;
headers:Headers;
options:RequestOptions;
constructor(public navCtrl: NavController, private loadingCtrl:
LoadingController, public navParams: NavParams, private
httpProvider:HttpProvider, public http:Http) {
}
ionViewDidLoad() {
console.log('ionViewDidLoad SamplePage');
}
loadJson(){
let headers = new Headers();
headers.append('Content-Type', 'application/x-www-form-urlencoded;
charset=UTF-8');
let options = new RequestOptions({ headers: headers });
let data="token="+""+
"&searchvalue="+""+
"&sortby="+""+
"&sorttype="+""+
"&filter="+""+
"&startfrom="+""+
"&limit="+""+
"&producttype=1";
this.http.post('this is my API URL', data, options)
.map(res => res.json())
.subscribe(res => {
this.users = res.data;
console.log(this.users);
},
(err) => {
alert("failed to load json data");
});
}
}
这是我的离子html 的 sample.html
<button ion-button (click)="loadJson()">Load Data</button>
<ion-list>
<ion-item class="col" *ngFor="let user of users" >
<p class="t"> {{user.productid}}</p>
<ion-icon class="icon" name="ios-heart-outline" md="md-heart"></ion-icon>
<br>
<p class="p">ProductId : {{user.name}}</p>
<!--<img class="img" src="{{user.productImg}}" width="97px"
height="86px" ng-click="nextpage()"> 
<p class="p">Rs {{user.price}}</p>
--><hr>
</ion-item>
</ion-list>
请给我一些建议或想法。 提前谢谢。
答案 0 :(得分:0)
我只是在离子中包含js来实现url中的body参数
sup(){
$.post("http:xxxxxxxxxx/"+"listProducts",
{
"token" : '' ,
"searchvalue" : '' , //Product Name
"sortby" : '' , //Brand
"sorttype" : '' , //asc,desc
"filter" : '' , //Category
"startfrom" : '' , //1,2, etc
"limit" : '', //1,10,4,5, etc
"producttype" : '1' //1 Suppliments or 2 accessories
},
function(data,status){
var d = JSON.parse(data);
}
}
此代码成功从API检索JSON数据 我希望这对其他人有用 谢谢
答案 1 :(得分:0)
您可以直接使用ionic而不是js来调用API
var link = "Your API";
var body = JSON.stringify({mno: mobile,pwd: password});
return new Promise(resolve=>{
this.http
.post(link,body)
.map(res=>res.json())
.subscribe((data : any) =>
{
this.items = data;
console.log(this.items);
},
(error : any) =>
{
console.dir(error);
});
});