我在尝试提交数据时出错-Angular



你好,我想向服务器提交数据时遇到问题。这是我的代码:

服务.ts:

@Injectable({providedIn: 'root'})
export class ArticlesService {
constructor(private http: HttpClient) { }
createArticle(title: string, body: string, categoryId: number) {
const postData: Article = { title: title, body: body, categoryId: categoryId};
const url = 'http://18.192.182.140/api/articles?api_token=9aK4W3D7NpbWwPzJmUOIcyPmyehl0PHZLWP14rzQqKzUPtcFCo0Tn051CvwN';
return this.http.post(url, postData)
}
}

型号:

export interface Article {
title: string;
body: string;
categoryId: number;
}

Article Component.ts:

@Component({
selector: 'app-new-article',
templateUrl: './new-article.component.html',
styleUrls: ['./new-article.component.css']
})
export class NewArticleComponent implements OnInit {
constructor(private articleService: ArticlesService) { }
ngOnInit(): void { }
createNewArticle(postData: Article) {
this.articleService.createArticle(postData.title, postData.body, 
postData.categoryId).subscribe(responseData => {
console.log(responseData);
});;

}

Article.html:

<div class="container">
<h1>Add New Article</h1>
<div class="row">
<div class="col-xs-12 col-sm-10 col-md-8 col-sm-offset-1 col-md-offset-2">
<form #postForm="ngForm" (ngSubmit)="createNewArticle(postForm.value)">
<div id="user-data">
<div class="form-group">
<label for="title">Title</label>
<input type="text" id="title" class="form-control">
</div>
<div class="form-group">
<label for="body">Body</label>
<input type="text" id="body" class="form-control">
</div>
<div class="form-group">
<label for="category_id">Category ID</label>
<input type="number" id="category_id" class="form-control">
</div>
</div>
<button class="btn btn-primary" type="submit">Add new Article</button>
<button class="btn btn-primary" type="button" routerLink="/admin">Cancel</button>
</form>
</div>

当我点击";添加新文章";按钮我得到这个错误:

ERROR HttpErrorResponse {headers: HttpHeaders, status: 200, statusText: 'OK', url: 
'http://18.192.182.140/api/articles?api_token=9aK4W… 
WwPzJmUOIcyPmyehl0PHZLWP14rzQqKzUPtcFCo0Tn051CvwN', ok: false, …}

任何人都知道如何解决这个错误,我试图将responseType设置为";文本";但它不起作用。谢谢

我认为您没有发送表单中获得的信息看看这个:https://angular.io/api/forms/NgModelGroup

在component.ts中,他们通过onsubmit((获得信息,我在您的代码中看不到类似的东西,请尝试在"行之前添加console.log;this.articleService.createArticle(postData.title,postData.body,"以确保您正在发送

最新更新