Search code examples
angulartypescriptapiangular-services

Angular 2 post method gives typescript error


I am using Angular 2 And I interact with an API through a service.
I have a method that I want to use for posting into the API.

ERROR in src/app/application/users/create-new-user/create-new-user.component.ts(146,5): error TS2554: Expected 0 arguments, but got 1.

user.ts code

var submitData =
{
  first_name: formData.firstName,
  last_name: formData.lastName,
  email: formData.email,
  password: formData.password,
  address_1: formData.address1,
  address_2: formData.address2,}

his.appService.createUser(submitData).subscribe((result: any) => {
  if (result != '') {

appservice.ts

createUser(): Observable<any> {

  const headers = new HttpHeaders()
    .set('security-token', localStorage.getItem('loginToken'));

  return this.http.post<any>(this.basePath + '/user-groups', { headers })
    .pipe(
      map((response => {
        return response.data;
      }))

Solution

  • There are Many Mistakes in the Code Mentioned. I will Point them out as per relevance. 1.Argument Passed Must be defined in createUser Function. 2.You are only setting header and not passing any data in the POST request which is your main purpose. 3. You must not return response.data instead just return output of the POST method as the return type of createUser is Observable .

    So the Correct way to write the Code must be :

    createUser(data:any): Observable {

    const headers = new HttpHeaders().set('security-token', localStorage.getItem('loginToken'));

    return this.http.post(this.basePath + '/user-groups', data, {headers: headers}) }