如何创建一个PUT方法来更新用户

时间:2019-06-25 16:52:47

标签: angular typescript rest webstorm

尝试从我的网站更新数据库中的用户。在下面,您可以看到我用来从数据库中获取数据并且可以正常运行的代码,但是我无法从html.component(MySQL)的输入字段中更新数据库中的数据

settings.component.ts

export class SettingsComponent implements OnInit {

  settings = {
    username: '',
    email: '',
    password: ''
  };

  constructor(private http: HttpClient) { }

  baseUrl = 'http://localhost:8080/aquadine-jee/resources/user';

  ngOnInit() {
    //Get data from baseUrl(variable above url to the backend)
    this.http.get(this.baseUrl)
      .subscribe(
        val => {
          const usernameField = val;
          // @ts-ignore
          const usernameNaam = JSON.stringify(usernameField[usernameField.length - 1].username);
          console.log(usernameField);
          console.log(usernameField[0].username);
          this.settings.username = usernameNaam.slice(1, usernameNaam.length - 1);
        }
      );

    this.http.get(this.baseUrl)
      .subscribe(
        val => {
          const emailField = val;
          // @ts-ignore
          const emailNaam = JSON.stringify(emailField[emailField.length - 1].email);
          console.log(emailField);
          console.log(emailField[0].email);
          this.settings.email = emailNaam.slice(1, emailNaam.length - 1);
        }
      );

    this.http.get(this.baseUrl)
      .subscribe(
        val => {
          const passwordField = val;
          // @ts-ignore
          const passwordNaam = JSON.stringify(passwordField[passwordField.length - 1].password);
          console.log(passwordField);
          console.log(passwordField[0].password);
          this.settings.password = passwordNaam;
          this.settings.password = passwordNaam.slice(1, passwordNaam.length - 1);
        }
      );

    this.http.put(this.baseUrl, this.settings.username)
      .subscribe(
        val => {

        }
      );

}
}

这是来自后端的:

 /**
     * Updates individual user
     * @param user
     * @return updated user
     */
    @PUT
    @Consumes("application/json")
    public Response update(User user){
        repositoryService.update(user);
        return Response
                .status(200)
                .entity(user)
                .build();
    }

有人可以帮助我提供从数据库中获取数据所必须使用的正确PUT方法。

1 个答案:

答案 0 :(得分:0)

   this.http.get(this.baseUrl)
  .subscribe(
    val => {
      const usernameField = val;
      // @ts-ignore
      const usernameNaam = JSON.stringify(usernameField[usernameField.length - 1].username);
      console.log(usernameField);
      console.log(usernameField[0].username);
      this.settings.username = usernameNaam.slice(1, usernameNaam.length - 1);

      this.http.put(this.baseUrl, this.settings.username)
        .subscribe(
          val => {
            console.log(val);
          }
        );
    }
  );

这是您可以尝试的最简单的方法(但是在.subscribe()中进行异步操作是一种不好的做法)。