Я создаю пустой проект.
Это простой проект, который получает и публикует данные, используя веб-API asp.net. Я получаю сообщение об ошибке при использовании почтового метода.
Сообщение об ошибке:
Тип медиа объекта запроса 'text / plain' не поддерживается для этого
ресурс.
Я подумал, что отсутствует, чтобы установить тип содержимого HTTP-запроса json. Поэтому я добавил опцию к методу post, который все еще не работает. Ниже прилагается скриншот запроса и ответа
Код:
package.json:
{
"name": "addEmployee",
"version": "0.0.1",
"author": "Ionic Framework",
"homepage": "http://ionicframework.com/",
"private": true,
"scripts": {
"clean": "ionic-app-scripts clean",
"build": "ionic-app-scripts build",
"lint": "ionic-app-scripts lint",
"ionic:build": "ionic-app-scripts build",
"ionic:serve": "ionic-app-scripts serve"
},
"dependencies": {
"@angular/animations": "5.2.10",
"@angular/common": "5.2.10",
"@angular/compiler": "5.2.10",
"@angular/compiler-cli": "5.2.10",
"@angular/core": "5.2.10",
"@angular/forms": "5.2.10",
"@angular/http": "5.2.10",
"@angular/platform-browser": "5.2.10",
"@angular/platform-browser-dynamic": "5.2.10",
"@ionic-native/core": "4.7.0",
"@ionic-native/splash-screen": "4.7.0",
"@ionic-native/status-bar": "4.7.0",
"@ionic/storage": "2.1.3",
"ionic-angular": "3.9.2",
"ionicons": "3.0.0",
"rxjs": "5.5.10",
"sw-toolbox": "3.6.0",
"zone.js": "0.8.26"
},
"devDependencies": {
"@ionic/app-scripts": "3.1.9",
"typescript": "~2.6.2"
},
"description": "An Ionic project"
}
зачислить-user.html
<ion-list>
<ion-item>
<ion-label floating>Name</ion-label>
<ion-input type="text" [(ngModel)]="userData.Name"></ion-input>
</ion-item>
<ion-item>
<ion-label floating>Location</ion-label>
<ion-input type="text" [(ngModel)]="userData.Location"></ion-input>
</ion-item>
<ion-item>
<ion-label floating>Id</ion-label>
<ion-input type="text" [(ngModel)]="userData.Id"></ion-input>
</ion-item>
<button ion-button full color="success" (click)="signup()">Save</button>
</ion-list>
зачислить-user.ts
//import { Component } from '@angular/core';
//import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Component } from '@angular/core';
import { NavController} from 'ionic-angular';
import { WebapiServiceProvider } from '../../providers/webapi-service/webapi-service';
@Component({
selector: 'page-enroll-user',
templateUrl: 'enroll-user.html',
})
export class EnrollUserPage {
responseData : any;
userData = {"Name": "","Location": "", "Id": ""};
constructor(public navCtrl: NavController, public webService:WebapiServiceProvider) {
}
signup(){
this.webService.postData(this.userData,'Enrollment').then((result) => {
this.responseData = result;
if(this.responseData.userData){
console.log(this.responseData);
}
else{ console.log("User already exists"); }
}, (err) => {
// Error log
});
}
ionViewDidLoad() {
console.log('ionViewDidLoad EnrollUserPage');
}
}
webapi-service.tc
import {Injectable} from '@angular/core';
import {Http, Headers} from '@angular/http';
import 'rxjs/add/operator/map';
/*
Generated class for the WebapiServiceProvider provider.
See https://angular.io/guide/dependency-injection for more info on providers
and Angular DI.
*/
let apiUrl = 'http://localhost:4440/api/'; //this works fine using postman
@Injectable()
export class WebapiServiceProvider {
constructor(public http : Http) {
console.log('Hello WebapiServiceProvider Provider');
}
postData(credentials, type) {
return new Promise((resolve, reject) => {
let headers = new Headers();
headers.append('Content-Type','application/json; charset=utf-80');
this.http.post(apiUrl + type, JSON.stringify(credentials), {headers: headers})
.subscribe(res => {
resolve(res.json());
}, (err) => {
reject(err);
});
});
}
}
РЕДАКТИРОВАННАЯ ВЕРСИЯ: Использование httpclient и httpHeader
import {Injectable} from '@angular/core';
//import {HttpClient , HttpHeaders } from '@angular/common/http';
//import 'rxjs/add/operator/map';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
/*
Generated class for the WebapiServiceProvider provider.
See https://angular.io/guide/dependency-injection for more info on providers
and Angular DI.
*/
let apiUrl = 'http://localhost:4440/api/';
@Injectable()
export class WebapiServiceProvider {
private _headers = new HttpHeaders().set('Content-Type', 'application/json; charset=utf-80');
constructor(public http : HttpClient) {
console.log('Hello WebapiServiceProvider Provider');
}
postData(credentials, type) {
return new Promise((resolve, reject) => {
// const headers = this._headers.append('Content-Type','application/json; charset=utf-80');
const headers=this._headers;
// let headers = new HttpHeaders();
// headers.append('Content-Type','application/json; charset=utf-80');
// headers = headers.append('Content-Type','application/json; charset=utf-80');
this.http.post(apiUrl + type, JSON.stringify(credentials), {headers: headers})
.subscribe(res => {
resolve(res);
}, (err) => {
reject(err);
});
});
}
}
Asp.net Webapi:
Это прекрасно работает с почтальоном
[HttpPost]
[Route("api/Enrollment", Name = "PropertyRoute")]
public clsEnrolResponse Insert(clsEnrolRequest objRequest)
{
clsEnrolResponse objResponse = new clsEnrolResponse();
try
{
if (objRequest.Name != null || objRequest.Name.Trim() != "")
{
if (objRequest.Location == null)
{
objRequest.Location = "";
}
int iResult = clsDB.InsertBookingInfo_Temp(objRequest);
objResponse.EnrolmentID = objRequest.Id;
objResponse.Status = "Success";
HttpResponseMessage message = new HttpResponseMessage();
message = Request.CreateResponse(HttpStatusCode.OK);
}
else
{
objResponse.Status = "ERROR";
objResponse.ErrorMsg = "Name is blank!!";
objResponse.EnrolmentID = "-1";
}
}
catch (Exception ex)
{
objResponse.Status = "ERROR";
objResponse.EnrolmentID = "-1";
objResponse.ErrorMsg = ex.Message.ToString();
}
return objResponse;
}
IMG1:
IMG2: