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

时间:2017-02-21 09:53:24

标签: java angular java-ee frontend backend

我尝试使用Angular2为FrontEnd和JavaE为BackEnd创建一个应用程序。通过一些演示,我终于明白了数据是如何交换的,但是当我想要在表中收回一个元素时,我遇到了一个小问题。

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

并得出结论,在地址&#34; http://localhost:8080/SWBackend/jaxrs/Person&#34;,我有我的人名单,所以它很好,并且在&#34; http://localhost:8080/SWBackend/jaxrs/Person/5 &#34;我有我想要的人,但我不明白为什么我无法展示它。

1 个答案:

答案 0 :(得分:0)

试试这个

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

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

使用? angular即使数据不存在也不允许抛出任何错误