简体   繁体   中英

Not able to send Object to rest API in angular 6

I am consuming Rest API and wants to save User Data, i am able to hit the API but not able to send the object. Its showing null in API.

I checked my console and network, its showing the angular application URL not the API URL.

export class UserService {
  url = 'http://localhost:8085/api/employees';
  constructor(private http: HttpClient) {}

  userData(user: User): Observable<any> {
    const params = new HttpParams().set('id', '5').
    set('userName', 'Bisnu').set('salary', '100').set('department', 'IT').set('password', 'mohan')
    .set('firstName', 'Bisnu').set('lastName', 'Biswal');
    const newUser = {
      userName: 'Bisnu',
      salary: 100,
      password: 'mohan',
      department: 'IT',
      firstName: 'Bisnu',
      lastName: 'Mohan'
    };

    console.log(newUser);
    console.log(this.url);
    return this.http.post<any>(this.url, newUser);
  }
}

and from component i am calling this service

onSubmit(){
    console.log(this.user);
    this.userService.userData(this.user).subscribe(
      data => console.log("success", data),
      error => console.error("Error!",error)
    );
    this.resetForm();
  }
}

Browser console i checked it is as below, which is wrong.

在此处输入图片说明

the controller is as below

在此处输入图片说明

The User model is as below

在此处输入图片说明

Try this, backend object and your newuser object does not match.

    userData(user: User): Observable<any> {
          user.Id :1;
          user.userName: 'Bisnu';
          user.salary: 100;
          user.password: 'mohan';
          user.department: 'IT';
          user.firstName: 'Bisnu';
          user.lastName: 'Mohan';

        return this.http.post<any>(this.url, user);
      }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM