【发布时间】:2019-05-25 17:42:20
【问题描述】:
我正在尝试从 tomcat 服务器获取数据到 Angular 应用程序。 在我的 tomcat 服务器上,我有一个返回 json 的链接 在我的 Angular 应用程序中,我尝试使用 httpclient 和 httpheader 获取 json。
当我将 Angular 代码中的链接复制到浏览器时,浏览器会接受它。然后在 tomcat 服务器的终端中显示一条系统消息。 但是,当我运行 Angular 代码时,没有显示终端消息,并且在 Angular 应用程序的控制台日志中,我看到了如下所示的错误。
以下是生成 json 响应的 java 方法。系统输出语句按预期显示 json。
public String toJSON(Object object) throws JsonProcessingException
{
ObjectMapper mapper = new ObjectMapper();
return mapper.writeValueAsString(object);
}
private void getAllUser(HttpServletRequest request, HttpServletResponse response) throws IOException
{
System.out.println("en deze request is GET-ALL-USERS ");
String userJSON = this.toJSON(model.getPersons());
System.out.println("en deze request is GET-ALL-USERS = " + userJSON);
response.setContentType("application/json");
response.getWriter().write(userJSON);
}
接收 json 的角码:
import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
import { Gebruiker } from './gebruiker';
import { MessageService } from './message.service';
import { Observable, of } from 'rxjs';
import { catchError, map, tap } from 'rxjs/operators';
const httpOptions = {
headers: new HttpHeaders({ 'Content-Type': 'application/json' })
};
@Injectable({
providedIn: 'root'
})
export class GebruikerService {
private urlGetAllUsers = 'http://localhost:8081/Controller?action=angular&asyncAction=getAllUsers';
constructor(
private http: HttpClient,
private messageService: MessageService) {
}
/** GET gebruikers from the server */
getGebruikers (): Observable<Gebruiker[]> {
const url = `${this.urlGetAllUsers}`;
return this.http.get<Gebruiker[]>(url)
.pipe(
tap(_ => this.log('fetched gebruikers')),
catchError(this.handleError('getGebruikers', []))
);
}
private handleError<T> (operation = 'operation', result?: T) {
return (error: any): Observable<T> => {
// TODO: send the error to remote logging infrastructure
console.error(error); // log to console instead
// TODO: better job of transforming error for user consumption
this.log(`${operation} failed: ${error.message}`);
// Let the app keep running by returning an empty result.
return of(result as T);
};
}
}
我在控制台中收到的错误消息:
{body: {…}, url: "http://localhost:8081/Controller?action=angular&asyncAction=getAllUsers", headers: HttpHeaders, status: 404, statusText: "Not Found"}
body: {error: "Collection 'undefined' not found"}
headers: HttpHeaders
lazyInit: ƒ ()
lazyUpdate: null
normalizedNames: Map(0) {}
__proto__: Object
status: 404
statusText: "Not Found"
url: "http://localhost:8081/Controller?action=angular&asyncAction=getAllUsers"
__proto__: Object
我希望有人可以帮助我。 谢谢
【问题讨论】:
标签: angular typescript angular-httpclient