2017-08-14 109 views
0

如果我能看到网站的价值,为什么会出现这种错误?......怎么了?为什么我会显示“无法读取属性”类型的“未定义”?

这是代码,基本上,它的工作,但在控制台的错误

students.component.html

<li class="list-inline-item"> 
    <figure> 
     <img [src]="car.details.type.icon"> 
      <figcaption class="whiptype__value">{{ car.details.type.name }}</figcaption> 
      </figure> 
</li> 

students.service.ts

get(): Observable<string[]> { 
    return this.http.get('assets/data/cars.json') 
     .map((res: Response) => res.json()) 
        // .do(data => console.log('server data:', data)) // debug 
     .catch(this.handleError); 
    } 

    getById(id: string): Observable<string[]> { 
    return this.get().map(
     (res) => { 
     let filterResult = res.filter(item => {   
      return item.id === id 
     }); 
     // console.log(filterResult[0]); 

     return filterResult[0]; 
     }).catch(this.handleError); 
    } 

students.component.ts

getStudentById (id:number){ 
    this.studentService.getById(id) 
     .subscribe(
     student => this.student = student, 
     error => this.errorMessage = <any>error 
    ); 
    } 

这个数据是如何返回 JSON响应

{id: "3", details:{ type:{ name: "ferrari", icon: "assets/icons/car-details/ferrari.png" }}} 
+0

您正在尝试在数据加载之前访问它,以便您收到该错误,但一旦加载,您就可以看到它。 –

+0

这是有道理的....也当我做'汽车| json'我得到一个安全错误,这就是为什么我在服务中使用'filterResult [0]' –

回答

1

这里使用安全导航操作,因为你试图数据之前访问它收到

<figure> 
<img [src]="car?.details?.type?.icon"> 
<figcaption class="whiptype__value">{{ car?.details?.type?.name }}</figcaption> 
</figure> 
相关问题