我尝试使用 Angular2 作为前端,使用 JavaEE 作为后端来创建一个应用程序。通过一些演示,我终于了解了数据是如何交换的,但是当我想恢复表中的一个元素时,我遇到了一些问题。
person.service.ts 中的代码:
export class PersonService {
private baseUrl: string = 'http://localhost:8080/SWBackend/jaxrs';
constructor(private http: Http) {}
get(id: number): Observable<Person> {
let person$ = this.http
.get(`${this.baseUrl}/Person/${id}`, {headers: this.getHeaders()})
.map(mapPerson);
return person$;
}
private getHeaders() {
let headers = new Headers();
headers.append('Accept', 'application/json');
headers.append('Content-Type', 'application/json');
return headers;
}
}
function mapPerson(response: Response): Person {
return toPerson(response.json());
}
function toPerson(r: any): Person {
return r;
}
在我的 person.component.ts 中:
export class PersonComponent implements OnInit{
people: Person[] = [] ;
pre: Person;
constructor(private personService: PersonService){}
ngOnInit(){
this.personService
.get(5)
.subscribe(p => this.pre = p);
this.personService.getAll().subscribe(p => this.people = p);
// I get another method getAll who list all the people
// and works with almost the same code as get
}
}
在我的模板中,我这样做了:
<p> {{pre.id}}</p>
我得到了这种类型的错误:
Cannot read property 'id' of undefined
最后,在地址“http://localhost:8080/SWBackend/jaxrs/Person”,我有我的人员列表,所以这很好,在“http://localhost:8080/SWBackend/jaxrs/Person/5”我有我想要的人,但我不明白为什么我不能显示它。
最佳答案
试试这个
<p> {{pre?.id}}</p>
有时从数据库获取数据需要一些时间,并且 View 会在之前渲染,因此 Angular 会抛出这样的错误。
通过使用 ?
Angular 将不允许抛出任何错误,即使数据不存在
关于java - 在后端 Java EE 的表中使用 Angular2 获取一个元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42363986/