java - Spring Boot + Angular 5 - http.post 空值

标签 java html angular hibernate spring-boot

我正在开发一个客户端/服务器项目,并且使用 Spring Boot 和 Angular。

所以我有一个表单,我想从输入字段中获取数据并将其发送到后端,我的数据库( mySQL ),但问题是它只在我的数据库中添加空字段。我使用了 devglen 的教程作为灵感,并使用了 angular.io 的一些教程

表单输入示例:

<div class="form-group">
      <label for="body">Body:</label>
      <input type="text"  class="form-control" id="body"
             [ngModel]="article?.body" (ngModelChange)="article.body = $event" name="body">
    </div> 

我要添加的文章的模型类:

export class Article {
  id: string;
  title: string;
  abstract_art: string;
  writer: string;
  body: string;
}

我要添加的组件:

@Component({
  selector: 'app-add',
  templateUrl: './add-article.component.html'
})



export class AddArticleComponent  {



   article: Article = new Article();
   writers: Writer[];

  constructor(private router: Router, private articleService: ArticleService) {

  }
  createArticle(): void {
    console.log(this.article);
    this.articleService.createArticle( this.article).subscribe( data => { alert('Article created successfully.');
    });
    console.log('function called!');
  }

  get diagnostic() { return JSON.stringify(this.article); }
}  

服务类别:

const httpOptions = {
  headers: new HttpHeaders({ 'Content-Type': 'application/json',
    'Authorization': 'my-auth-token'})
};

@Injectable()
export class ArticleService {

  constructor(private http: HttpClient) {}

   // private userUrl = 'http://localhost:8080/articles';
  private articleUrl = '/api';

  public getArticles() {
    return this.http.get<Article[]>(this.articleUrl);
  }

  public deleteArticle(article) {
    return this.http.delete(this.articleUrl + '/' + article.id, httpOptions);
  }

  public createArticle(article) {
    // const art = JSON.stringify(article);
    console.log(article);
    return this.http.post<Article>(this.articleUrl, article);
  }

}

现在是后端。 文章类

@Entity
@Getter @Setter
@NoArgsConstructor
@ToString @EqualsAndHashCode
@Table(name="article")
public class Article {

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    private int id;

    @Column(name="title")
    private String title;

    @Column(name="abstract_art")
    private String abstract_art;

    @Column(name="writer")
    private String writer;

    @Column(name="body")
    private String body;

    public Article(String title,String abstract_art, String writer, String body) {
        this.title = title;
        this.body = body;
        this.abstract_art = abstract_art;
        this.writer = writer;

    }
}

存储库:

@RepositoryRestResource
//@CrossOrigin(origins = "http://localhost:4200")
public interface ArticleRepository extends JpaRepository<Article,Integer> {
}

文章服务:

@Service
public class ArticleServiceImpl implements ArticleService {

    @Autowired
    private ArticleRepository repository;

    @Override
    public Article create(Article article) {
        return repository.save(article);
    }

    @Override
    public Article delete(int id) {
        Article article = findById(id);
        if(article != null){
            repository.delete(article);
        }
        return article;
    }

    @Override
    public List<Article> findAll() {
        return repository.findAll();
    }

    @Override
    public Article findById(int id) {

        return repository.getOne(id);
    }

    @Override
    public Article update(Article art) {
        return null;
    }
}

Controller :

@RestController
@RequestMapping({"/api"})
public class ArticleController {

   @Autowired
   private ArticleService article;

    //Get all articles
    @GetMapping
    public List<Article> listAll(){
        return article.findAll();
    }

    // Create a new Article
    //@PostMapping
    @PostMapping
    public Article createArticle(Article art) {
        return article.create(art);
    }

    // Get a Single Article
    @GetMapping(value="/{id}")
    public Article getArticleById(@PathVariable("id") int id ){
        return article.findById(id);
    }

    // Delete a Note           /art/

    @DeleteMapping(value = "/{id}")
    public void deleteArticle(@PathVariable("id") int id) {
        article.delete(id);
    }

    @PutMapping
    public Article update(Article user){
        return article.update(user);
    }
}

In the picture you can see that it creates my json object but when i'm adding it to the database it only adds null values.

附加信息:我可以从数据库中获取数据,也可以从数据库中删除数据。

顺便说一句,这是我的第一篇文章,所以如果我错过了一些发帖指南,我很抱歉。 预先感谢您的答复。祝你玩得开心!

最佳答案

<强> @RestController 是一个方便的注释,它只不过是添加 @Controller @ResponseBody 注释并允许类接受发送到其路径的请求

@DOCS
@ResponseBody annotation tells a controller that the object returned is automatically serialized into JSON and passed back into the HttpResponse object.

@RequestBody annotation maps the HttpRequest body to a transfer or domain object, enabling automatic deserialization of the inbound HttpRequest body onto a Java object.

您错过了@RequestBody
@RequestBody 标记文章输入是从 POST 请求的正文/内容中检索的。这是 GETPOST 之间的显着区别,因为 GET 请求不包含正文。

修改后的代码

 @PostMapping
    public Article createArticle(@RequestBody Article art) {
        return article.create(art);
    }

关于java - Spring Boot + Angular 5 - http.post 空值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50437327/

相关文章:

html - 定位问题

node.js - angular-cli:为什么当 npm 安装新模块时,旧模块会被删除

angular - 如何销毁动态创建的组件 angular 8

java - 通过蓝牙将超声波传感器的数据从 Arduino 发送到 Android

java - 使用 QueryDSL JPA 在 MySQL 中查找重复的行

html - 垂直堆叠图像/视频

javascript - 如何在 localStorage 中存储数组?

java - 在 @Rule 中并行化测试执行

java - 查找和丢弃多边形之间的共享边

javascript - Angular SSR 网站在转到实际路径之前重定向到登录页面