2

I am working with angular 6 trying to send a post request using httpclient , but always receive null body on the server side.

 save( rules:RuleModel[]){

let _headers: HttpHeaders = new HttpHeaders({
  'Content-Type': 'application/json; charset=utf-8' 
});

return this._httpClient.post(AppConfig.BaseUrl,JSON.stringify(rules), {headers:_headers} );   } 

and API function

[HttpPost]
public List<Rule> AddTemplateTextRules( [FromBody]Rule[] Rules)
{
    try
    {
        return RuleManager.AddRule(Rules);
    }
    catch (Exception e)
    {
        return null;
    }
    return null; 
}

2 Answers 2

6

To make a post request in Angular 6 with standard practice you need to do followings:

In the service class:

import {throwError,  Observable } from 'rxjs';
import {catchError} from 'rxjs/operators';
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders, HttpParams, HttpErrorResponse } from '@angular/common/http';
import { Rule } from 'path';

@Injectable()
export class RuleService {
    constructor(private httpClient: HttpClient) { }
    private baseUrl = window.location.origin + '/api/Rule/';

    createTemplateTextRules(rules: Rules[]): Observable<boolean> {
       const body = JSON.stringify(rules);
       const headerOptions = new HttpHeaders({ 'Content-Type': 'application/json' });
       return this.httpClient.post<boolean>(this.baseUrl + 'AddTemplateTextRules', body, {
              headers: headerOptions
       }).pipe(catchError(this.handleError.bind(this));
    }

   handleError(errorResponse: HttpErrorResponse) {
     if (errorResponse.error instanceof ErrorEvent) {
        console.error('Client Side Error :', errorResponse.error.message);
     } else {
       console.error('Server Side Error :', errorResponse);
     }

    // return an observable with a meaningful error message to the end user
    return throwError('There is a problem with the service.We are notified & 
     working on it.Please try again later.');
   }
}

In the Component:

export class RuleComponent implements OnInit { 
    constructor(private ruleService: RuleService) { }
    createTemplateTextRules(): void {

    this.ruleService.createTemplateTextRules(rules).subscribe((creationStatus) => {
      // Do necessary staff with creation status
     }, (error) => {
      // Handle the error here
     });
   }
}

Then in the ASP.NET Core API Controller:

[Produces("application/json")]
[Route("api/Rule/[action]")]
public class RuleController : Controller
{
   [HttpPost]
   public Task<IActionResult> AddTemplateTextRules( [FromBody]Rule[] Rules)
   {
       try
       {
           return RuleManager.AddRule(Rules);
       }
       catch (Exception e)
       {
            return false;
       }
       return Json(true);
   }
}

Hope it will help you.

Sign up to request clarification or add additional context in comments.

5 Comments

Don't pass unbound methods as callbacks.
Tell me detail please.
catchError(this.handleError) is bad. If handleError references any other member of the class it will fail. Either use a free plain function, an arrow function, or .bind it to this. For more information read about how this works in JavaScript.
It turned out to be a problem with the object I send to the server have some wrong values. But now I can receive the list on the server. Thanks a lot ,, I just was very new to angular 2 this is why I thought there's something I can't understand
Glad to hear that your problem has been solved! Please accept the answer as right answer by clicking on check icon so that it can help others with the similar problems. Thank you.
0

With the latest RxJS(Angular 14) here is the way:

Service

  Login(phone:string,password:string)
  {
    let _headers: HttpHeaders = new HttpHeaders({
      'accept': 'application/json'
    });
    return this.http.post(this.url,{username,password},{headers:_headers})
                .pipe(map(response=>response));
  }

Component

  async Login(phone:string,password:string)
  {
    let token$ =  this.authService.Login(phone,password);
    let token = await lastValueFrom(token$);
  }

Since I was returning just text and not Json from the API, this was my code to handle text response type in the Service. If you're getting a response parse error, explicitly defining the responseType will help since Json is default.

  Login(phone:string,password:string)
  {
    let _headers: HttpHeaders = new HttpHeaders({
      'accept': 'text/plain'
    });
    return this.http.post(this.url+'security/login?phone='+phone+'&password='+password,null,{headers:_headers,responseType:'text'})
                .pipe(map(response=>response));
  }

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.