在后端 Java EE 中的 table 中使用 Angular2 获取一个元素

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

我尝试用 Angular2 为前端和 JavaEE 为后端制作一个应用程序。通过一些演示,我终于明白了数据是如何交换的,但是当我想在 table 中收回一个元素时,我遇到了一个小问题。

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", I have my list of person, so it's good, and at "http://localhost:8080/SWBackend/jaxrs/Person/5”我找到了我想要的人,但我不明白为什么我不能显示它。

试试这个

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

有时从数据库中获取数据需要一些时间,视图会在渲染之前呈现,因此angular会抛出这样的错误。

通过使用 ? angular 将不允许抛出任何错误,即使那里不存在数据也是如此