0

I am new to Angular 2 and I'm trying to POST data to Web API. For some reason my POST isn't working & I don't see the issue. The JSON.stringify works just fine...so my issue is probably the URL or the Service.

Any help appreciated.

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
}

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);
    }
}
Prisoner ZERO
  • 13,848
  • 21
  • 92
  • 137
  • Are you subscribing to it elsewhere? – Dylan May 19 '17 at 18:31
  • Not sure what you mean by SUBSCRIBING. But...this.http.post...does nothing. No Errors....no nothing. I hit break-points in the function – Prisoner ZERO May 19 '17 at 18:36
  • The observable http needs the subscription set ( normally in your component ) like - `yourService.submit().subscribe((data)=>{ ... })`. – Dylan May 19 '17 at 18:40
  • Possible duplicate of [Angular 2 http get not getting](http://stackoverflow.com/questions/41381200/angular-2-http-get-not-getting) – AT82 May 19 '17 at 19:11

2 Answers2

2

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());
 }
}
Arun Sivan
  • 1,680
  • 2
  • 12
  • 23
0

First, you need to subscribe. Also, usually the map method can be used as below:

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));
Patrik
  • 116
  • 1
  • 9