我有一个项目需要使用Angular2(final)发布到旧的,遗留的Tomcat 7服务器,使用.jsp页面提供一些REST-ish API.
当项目只是一个执行AJAX请求的简单JQuery应用程序时,这很好用.但是,项目的范围已经扩大,需要使用更现代的框架进行重写.Angular2对于这项工作看起来很棒,但有一个例外:它拒绝使用任何选项执行POST请求,但拒绝执行API不提取的表单数据.API期望所有内容都是urlencoded,依靠Java的request.getParameter("param")语法来提取单个字段.
这是从我的user.service.ts剪下来的:
import { Injectable } from '@angular/core';
import { Headers, Response, Http, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
@Injectable()
export class UserService {
private loggedIn = false;
private loginUrl = 'http://localhost:8080/mpadmin/api/login.jsp';
private headers = new Headers({'Content-Type': 'application/x-www-form-urlencoded'});
constructor(private http: Http) {}
login(username, password) {
return this.http.post(this.loginUrl, {'username': username, 'password': password}, this.headers)
.map((response: Response) => {
let user = response.json();
if (user) {
localStorage.setItem('currentUser', JSON.stringify(user));
}
}
);
} …Run Code Online (Sandbox Code Playgroud) 我难以克服"无法找到'对象'类型的'对象对象''的错误"这个错误似乎与Angular2非常相似,我希望有人遇到过类似的问题.
这是来自我服务的(匿名)JSON,非常简单:
[
{
"item_id": 1,
"item_type": 2,
"item_name": "Item 1",
"item_description": "First item"
},
{
"item_id": 2,
"item_type": 4,
"item_name": "Item 2",
"item_description": "Second item"
}
]
Run Code Online (Sandbox Code Playgroud)
这是描述这些对象的类,服务和组件的内容:
// item.ts
export class Item {
item_id: number;
item_type: number;
item_name: string;
item_description: string;
}
//item.service.ts snippet
getItems(): Promise<Item[]> {
return this.http.get('http://apiurl', { withCredentials: true })
.toPromise()
.then((response) => {
let body = response.json();
return body as Item[];
})
.catch(this.handleError);
}
//item.component.ts snippet
items: Item[];
getItems(): void { // Function that …Run Code Online (Sandbox Code Playgroud)