0

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);
    }
2
  • 1
    did you add cors service in your startup.cs file? Commented Aug 17, 2021 at 17:27
  • @PritomSarkar I have services.AddCors(); and app.UseCors(x => x .AllowAnyOrigin() .AllowAnyMethod() .AllowAnyHeader()); In my startup.cs file Commented Aug 17, 2021 at 17:30

3 Answers 3

1

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)
Sign up to request clarification or add additional context in comments.

Comments

1

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

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

1 Comment

It did not fix my problem, but you are right I do not need to and the JSON.stringify(family) in this case thank you for your help.
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.