简体   繁体   English

在后端Java EE的表中获取一个带Angular2的元素

[英]Get one element with Angular2 in a table in the backend Java EE

I try to make an application with Angular2 for the FrontEnd and JavaEE for the BackEnd. 我尝试使用Angular2为FrontEnd和JavaE为BackEnd创建一个应用程序。 By following some demo, I finally understand how the data are exchange but I got a little issue when I want to recoup one element in a table. 通过一些演示,我终于明白了数据是如何交换的,但是当我想要在表中收回一个元素时,我遇到了一个小问题。

The code in the person.service.ts : 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;
}

in my person.component.ts : 在我的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
    }
}

in my template, I did this : 在我的模板中,我这样做了:

<p> {{pre.id}}</p>

and I got this type of error : 我得到了这种错误:

Cannot read property 'id' of undefined

and to conclude, at the adress " http://localhost:8080/SWBackend/jaxrs/Person ", I have my list of person, so it's good, and at " http://localhost:8080/SWBackend/jaxrs/Person/5 " I have the person I want, but I don't understand why I can't display it. 并得出结论,在地址“ http:// localhost:8080 / SWBackend / jaxrs / Person ”中,我有我的人员列表,所以很好,并且在“ http:// localhost:8080 / SWBackend / jaxrs / Person / 5 “我有我想要的人,但我不明白为什么我不能展示它。

try this 尝试这个

<p> {{pre?.id}}</p>

sometimes it will take some time to get data from database and view will render before so angular will throw an error like this. 有时需要一些时间从数据库中获取数据并且视图将在之前呈现,因此angular会抛出这样的错误。

By using ? 通过使用? angular will not allow to throw any error even if data is not present there 即使数据不存在,angular也不允许抛出任何错误

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM