在Angular2中发布数据

时间:2017-05-19 17:37:28

标签: angular routing

我是Angular 2的新手,我正在尝试将数据发布到Web API。出于某种原因,我的POST不起作用&我没有看到这个问题。 JSON.stringify工作得很好......所以我的问题可能是网址或服务。

任何帮助表示感谢。

API CONTROLLER:

[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
}

数据服务组件:

// 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);
    }
}

2 个答案:

答案 0 :(得分:2)

示例代码

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() {}

}

<强>服务

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());
 }
}

答案 1 :(得分:0)

首先,您需要订阅。此外,通常map方法可以使用如下:

this.http.post(url, json, options)
  .map(response => response.json)
  .catch(error => this.handleError(error))
  .subscribe();

如果你还想做一些你可以做的事情:

this.http.post(url, json, options)
  .map(response => response.json)
  .catch(error => this.handleError(error))
  .subscribe(object => console.log(object));