J.C
J.C

Reputation: 752

Angular service NOT hiting Asp.Net MVC Post Controller

I have this method in my angular service I want it to hit a the controller in my asp.net CORE api. But it does not hit my controller. I have tried to make the post in Postman and it works. I do not understand why my post in Angular does not work Thank you for your help.

  addFamily(family: Family) {

    this.http.post<Family>('https://localhost:44344/api/componentFamily', JSON.stringify(family))
  }

Here is my ASP.NET CORE API.

    // POST api/componentFamily
    [HttpPost]
    public async Task<IActionResult> Post([FromBody] ComponenFamilyViewModel componentFamilyViewModel)
    {
        Family family = new Family();
        family.FamilyId = componentFamilyViewModel.FamilyId;
        family.FamilyName = componentFamilyViewModel.FamilyName;

        await _componentFamilyService.AddFamily(family);

        return CreatedAtAction("Get", new { id = family.FamilyId }, family);
    }

Upvotes: 0

Views: 431

Answers (3)

Antoniossss
Antoniossss

Reputation: 32517

Http client's observables are so called cold. In order for them to fire - and perform the web request - you have to subscribe to it, so

addFamily(family: Family) {

    return this.http.post<Family>('https://localhost:44344/api/componentFamily', JSON.stringify(family))
  }

and the caller

yourService.addFamily(famili).subscribe(result=>do whatever with the result)

Upvotes: 1

Some random IT boy
Some random IT boy

Reputation: 8457

Angular's HTTP client uses RxJS if you don't:

  1. Call .subscribe() (or with a callback)
  2. Call toPromise().then(val => {...})
  3. Use the async pipe from a template like so: <div *ngIf="response$ | async">

...the side-effect (network call) will not be performed.

Try the following:

@Component({...})
export class YourComponent {

  constructor(private http: HttpClient) {}

  public async onAddFamily(family: Family) {
     const response$ = this.http.post<Family>('https://localhost:44344/api/componentFamily', JSON.stringify(family))
     await response$.toPromise()
  }

Upvotes: 0

Nicola Biada
Nicola Biada

Reputation: 2800

Try to send the object without stringify if you use [FromBody]:

    this.http.post<Family>('https://localhost:44344/api/componentFamily', family)

Upvotes: 1

Related Questions