【发布时间】:2019-05-16 15:07:21
【问题描述】:
我正在尝试将表单中的数据发布到我的 REST 后端服务器,正在发布数据,但 httpclient.post 返回错误响应“发生错误:解析 [URL] 期间的 Http 失败”。
我已经尝试过类似问题所建议的修复,但没有找到任何适合 angular 7 的修复
import { Injectable } from '@angular/core';
import * as UrlConstants from './urls';
import { HttpClient, HttpErrorResponse, HttpHeaders } from '@angular/common/http';
import { Observable, throwError } from 'rxjs';
import { Book } from './book/book';
import { catchError } from 'rxjs/operators';
const httpOptions = {
headers: new HttpHeaders().set('Content-Type','application/json')
};
//import { RequestOptions, Request, RequestMethod } from '@angular/http';
@Injectable({
providedIn: 'root'
})
export class BookService {
private _getBooksUrl: string = UrlConstants.BOOKS_URL;
private _postBooksUrl: string = UrlConstants.POST_BOOK_URL;
constructor(private _http: HttpClient) { }
getAllBooks(): Observable<Book[]> {
console.log(this._getBooksUrl);
return this._http.get<Book[]>(this._getBooksUrl)
.pipe(catchError(this.errorHandler));
}
addBook(book: Book) {
let body = JSON.stringify(book);
return this._http.post<Book>(this._postBooksUrl, body, httpOptions)
.pipe(catchError(this.errorHandlerPost));
}
errorHandler(errorHandler: HttpErrorResponse): Observable<Book[]> {
return throwError(errorHandler.message || "server error");
}
errorHandlerPost(errorHandler: HttpErrorResponse) {
return throwError(errorHandler.message || "server error");
}
}
bookcomponent.ts
export class BookComponent implements OnInit {
public books = [];
public errorMessage;
book = new Book();
constructor(private _bookService: BookService) { }
ngOnInit() {
this.getBooks();
}
getBooks():void{
this._bookService.getAllBooks()
.subscribe(
data => {
this.books = data;
console.log(data)
},
error => {
this.errorMessage = error
console.log(error);
}
);
}
addBook():void{
this._bookService.addBook(this.book)
.subscribe(
(response) => {
console.log(response)
},
(error) => {
console.log("Error occurred :" + error);
}
);
}
}
【问题讨论】:
-
你也可以发
UrlConstants吗? -
post 中传递了什么httpOptions?
-
能否请您也发布控制台中发生的任何错误
-
const httpOptions = { headers: new HttpHeaders().set('Content-Type','application/json') };
-
发生错误:解析localhost:8080/BookAPI/api/create时的Http失败
标签: angular