简体   繁体   English

Spring Boot + Angular 5-http.post空值

[英]Spring Boot + Angular 5 - http.post null values

I'm working on a project client/server and I'm using spring boot and angular. 我正在使用项目客户端/服务器,并且正在使用spring boot和angular。

So I have a form and i want to take data from the input fields and send it to the back-end, my database ( mySQL ) but the problem is it only adds null fields in my database. 所以我有一个表单,我想从输入字段中获取数据并将其发送到后端数据库(mySQL),但是问题是它仅在数据库中添加了空字段。 I used a tutorial from devglen as inspiration and some tutorials from angular.io 我使用了devglen的教程作为灵感,并使用了angular.io的一些教程

Form input example: 表单输入示例:

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

Model class for the article i want to add: 我要添加的文章的模型类:

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

My component for adding: 我添加的组件:

@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); }
}  

The service class: 服务类别:

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);
  }

}

And now for the back-end. 现在是后端。 Article Class 文章类别

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

    }
}

The repository : 仓库:

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

The article service: 文章服务:

@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;
    }
}

And the 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. 在图片中,您可以看到它创建了我的json对象,但是当我将其添加到数据库时,它仅添加了空值。

Additional information: I can get data from database and I can delete data from database. 附加信息:我可以从数据库中获取数据,也可以从数据库中删除数据。

Btw it's my first post so i'm sorry if i've missed some guidelines for posting. 顺便说一句,这是我的第一篇文章,所以对不起,如果我错过了一些发布指南。 Thank you in advance for your answers. 预先感谢您的回答。 Have a good one! 祝你有个好的一天!

@RestController is a convenience annotation that does nothing more than adding the @Controller and @ResponseBody annotations as well as allows the class to accept the requests that are sent to its path @RestController是一个便捷注释,它除了添加@Controller@ResponseBody注释外, 无非就是允许类接受发送到其路径的请求。

@DOCS @DOCS
@ResponseBody annotation tells a controller that the object returned is automatically serialized into JSON and passed back into the HttpResponse object. @ResponseBody注释告诉控制器返回的对象会自动序列化为JSON,然后传递回HttpResponse对象。

@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批注将HttpRequest主体映射到传输或域对象,从而实现将入站HttpRequest主体自动反序列化到Java对象上。

You missed @RequestBody 您错过了@RequestBody
@RequestBody marks that the Article input is retrieved from the body/content of the POST request. @RequestBody表示从POST请求的正文/内容中检索Article输入。 This is a notable difference between GET and POST as the GET request does not contain a body. 这是GETPOST之间的显着区别,因为GET请求不包含正文。

Modified code 修改后的代码

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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