I found this, which is really out of date, and thus made this service (after some struggling) in an attempt to get a POST scenario working:
import {Injectable} from '@angular/core';
import {Observable} from 'rxjs/observable';
import {CampaignContract} from '../contracts/campaign.contract';
import {Campaign} from '../models/campaign.model';
import {Http, Response, Headers, RequestOptions} from '@angular/http';
import 'rxjs/add/operator/map';
@Injectable()
export class CampaignService implements CampaignContract {
public url:string;
constructor(private http: Http) {
this.url = "/api/campaign/";
}
public addCampaign(campaign: Campaign): Observable<Campaign> {
let headers = new Headers({ 'Content-Type': 'application/json' });
let options = new RequestOptions({ headers: headers });
let body = JSON.stringify(campaign);
return this.http.post(this.url, body, options).map((res: Response) =>
<Campaign>res.json());
};
}
The way I wired up some other things to test it is kind of silly for right now. What is above is what is important, not what is below. That said, my endpoint looks like this on the C# side:
using System.Web.Http;
using FluffyNothing.Core.Objects;
namespace FluffyNothing.UserInterface.Controllers
{
public class CampaignController : ApiController
{
public Campaign Post(Campaign campaign)
{
campaign.CampaignId = 13;
return campaign;
}
}
}
I'm sort of faking a classic object reshaping in a POST as would be true to the REST spec. The same object that gets handed in comes back to the user only now it has an id appended. The service is called by a component where it is assigned to a public property for an Observable of Campaign called observableCampaign. (Again, some silliness with these other pieces.) In the template for the component, I reference it like so:
<div *ngIf="observableCampaign">
look: {{tryToMakeSense(observableCampaign | async)}}
</div>
My goofy tryToMakeSense method on my component looks like this:
tryToMakeSense(campaign:Campaign):number{
console.log('logging');
console.log(campaign);
if (campaign){
return campaign.CampaignId;
} else {
return 0;
}
}
You kind of have to Observable bleed things all the way up to the HTML markup to test them with enough attention/pinging to get them to bring something back that you may, well, observe. Clearly this is not going to be applicable in a PUT or a DELETE implementation which should be fire and forget flavored per the REST spec. In trying to craft the service I struggled to even hit my endpoint for the longest time because I was screwing up the code for the headers initially (again, the blog post I'm referencing is troubled), and only in getting error messages back from stuff logged to the console could I really troubleshoot what was wrong. Had I started with a PUT or DELETE approach I'd probably still be scratching my head.
No comments:
Post a Comment