Hey (1st time posting here so I may break some rules, tell me if I do),
I'm trying to create a Rest API and I have some problems with. In fact, the post function is not triggered on the C# API and I don't know why while the GET function used with a getAll() function is running good.
Angular Service :
public GetAll = (): Observable<Expertise[]> => {
return this.http.get(this.actionUrl, '').map((response: Response) => <Expertise[]>response.json());
}
public Add = (thingToAdd: Expertise): Observable<Expertise> => {
thingToAdd.Id = 1;
let toAdd = JSON.stringify(thingToAdd);
console.log(toAdd);
console.log(this.actionUrl);
return this.http.post(this.actionUrl, toAdd, { headers: this.headers
}).map((response: Response) => response.json());
}
C# API :
// GET api/values
[HttpGet]
public async Task<IEnumerable<Expertise>> Get()
{
try
{
System.Console.WriteLine("Test get all");
//var result = await cvService.Get("toto@azeo.com");
return new List<Expertise>();
}
catch (System.Exception ex)
{
logger.LogError(ex.Message, ex);
throw;
}
}
// POST api/values
[HttpPost]
public Expertise Post([FromBody]Expertise expertise)
{
try
{
System.Console.WriteLine("Test post");
context.Expertises.Add(expertise);
context.SaveChanges();
logger.LogInformation("New expertise added !");
return expertise;
}
catch (System.Exception ex)
{
logger.LogError(ex.Message, ex);
throw;
}
}
Expertise (EF model) :
public class Expertise
{
[Key]
public int Id { get; set; }
public string Name { get; set; }
public ICollection<ExpCV> CVs { get; set; }
}
If anyone has an idea to "link" the service and my API tell me, I'm stuck on it for a since a long time.
Thank you in advance
since your service returns an observable
the actual GET
and POST
requests will NOT happen until you subscribe to that observable.
take a look at this plunker I set up:
plunker: https://plnkr.co/edit/r6aBaB3BjJzdIS4myAd8?p=preview
code:
@Component({
selector: 'app',
template: `
<button (click)="searchNoSub()">searchNoSub</button>
<button (click)="search()">search</button>
`
})
export class App {
constructor(private searchService:SearchService) {
}
search(){
this.searchService.search().subscribe(console.log,console.log)
}
searchNoSub(){ this.searchService.search(); }
}
searhService:
@Injectable()
export class SearchService {
constructor(private http: Http) {}
search(term: string) {
// get artists named john from spotify API
return this.http.get('https://api.spotify.com/v1/search?q=john&type=artist')
.map((response) => response.json());
}
}
now open your devtools and network
tab in chrome to look at new requests:
when clicking the searchNoSub
you'll notice no requests are registered in network tab.
when clicking search
button, you'll see a request because we subscribed.
In short, you need to subscribe to the request observable.