[英]Posting Data in Angular2
I am new to Angular 2 and I'm trying to POST data to Web API. 我是Angular 2的新手,正在尝试将数据发布到Web API。 For some reason my POST isn't working & I don't see the issue.
由于某种原因,我的POST无法正常工作,并且我看不到该问题。 The
JSON.stringify
works just fine...so my issue is probably the URL or the Service. JSON.stringify
可以正常工作...所以我的问题可能是URL或服务。
Any help appreciated. 任何帮助表示赞赏。
API CONTROLLER: API控制器:
[Route("api/[controller]")]
public class SamplesController : Controller
{
#region <Actions>
// GET: api/samples/list
[HttpGet("[action]")]
public IEnumerable<SampleData> List()
{
return UnitOfWork.Samples.AsEnumerable();
}
[HttpPost("[action]")]
public void Post([FromBody]string value)
{
// Never gets here
}
#endregion
}
DATA SERVICE COMPONENT: 数据服务组件:
// MODULES
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Headers, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map';
// MODELS
import { SampleDataModel } from "../models/sampledata.model";
@Injectable()
export class SampleDataService {
// CONSTRUCTORS
constructor(private http: Http) { }
// METHODS - public
public submit(sample: SampleDataModel) {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
let url: string = 'api/samples/post';
let json = JSON.stringify(sample);
return this.http.post(url, json, options)
.map(this.extractData)
.catch(this.handleError);
}
}
Sample Code 样例代码
import { Component, OnInit,ElementRef,Directive, Attribute } from '@angular/core';
import {SampleDataService} from '../shared/sampledataservice.service';
import { RouterModule, Router } from '@angular/router';
@Component({
selector: 'your selector',
templateUrl: './yourfile.html',
styleUrls: ['./yourfile.css']
})
export class yourclass implements OnInit{
constructor(public fetchData:SampleDataService,private router: Router)
{
this.fetchData=fetchData;
}
postData(myForm){
postMapHeader=some object;
this.fetchData.submit(postMapHeader).subscribe(res=>{
returnMap=res;
});
}
ngOnInit() {}
}
Service 服务
import { Injectable ,OnInit,OnDestroy} from '@angular/core';
import { Http, Response,Headers,RequestOptions} from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/Rx';
import 'rxjs/add/operator/map';
@Injectable()
export class SampleDataService {
data:any; //assign your data here
baseUrl:string='http://your url';
constructor(public http:Http) { }
submit(data){
let jsonData = JSON.stringify(data);
let object = JSON.parse(jsonData);
let headers = new Headers({ 'Content-Type': 'application/json'});
let options = new RequestOptions({ headers: headers });
return this.http.post(`${this.baseUrl}/yourapi`,object,options)
.map(result=>result.json());
}
}
First, you need to subscribe. 首先,您需要订阅。 Also, usually the map method can be used as below:
此外,通常可以按以下方式使用map方法:
this.http.post(url, json, options)
.map(response => response.json)
.catch(error => this.handleError(error))
.subscribe();
If you also want to to something with the response you can do like: 如果您还想对响应有所帮助,可以执行以下操作:
this.http.post(url, json, options)
.map(response => response.json)
.catch(error => this.handleError(error))
.subscribe(object => console.log(object));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.