Spring Boot + Angular 5 - http.post null值

时间:2018-05-20 17:01:16

标签: java html angular hibernate spring-boot

我在项目客户端/服务器上工作,我使用弹簧启动和角度。

所以我有一个表单,我想从输入字段中获取数据并将其发送到后端,我的数据库(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;
    }
}

控制器:

@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.

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

顺便说一句,这是我的第一篇文章,所以如果我错过了一些发布指南,我很抱歉。 提前感谢您的回答。有一个好的!

1 个答案:

答案 0 :(得分:3)

@RestController 是一种便利注释,只需添加 @Controller @ResponseBody 注释以及允许类接受发送到其路径的请求

  

<强> @DOCS
   @ResponseBody注释告诉控制器该对象   返回自动序列化为JSON并传回   HttpResponse对象。

     

@RequestBody注释将HttpRequest主体映射到传输或   域对象,启用入站的自动反序列化   将HttpRequest主体放到Java对象上。

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

修改后的代码

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