【发布时间】:2017-09-18 17:33:38
【问题描述】:
这是开发者控制台中的错误消息
错误类型错误:无法读取属性“restaurant_name”的 不明确的 在 Object.eval [作为 updateRenderer] (RestaurantDetailComponent.html:2) 在 Object.debugUpdateRenderer [作为 updateRenderer] (core.es5.js:13094) 在 checkAndUpdateView (core.es5.js:12241) 在 callViewAction (core.es5.js:12601) 在 execComponentViewsAction (core.es5.js:12533) 在 checkAndUpdateView (core.es5.js:12242) 在 callViewAction (core.es5.js:12601) 在 execEmbeddedViewsAction (core.es5.js:12559) 在 checkAndUpdateView (core.es5.js:12237) 在 callViewAction (core.es5.js:12601) ...
但是在我的详情页中,restaurant_name中的值实际上是显示出来的。
这里是详细页面实现的代码: 文件:restaurant-detail.component.ts
import { Component, OnInit, Input } from '@angular/core';
import { Restaurant } from '../restaurant';
import { RestaurantService } from '../restaurant.service';
import { ActivatedRoute } from '@angular/router';
@Component({
selector: 'app-restaurant-detail',
templateUrl: './restaurant-detail.component.html',
styleUrls: ['./restaurant-detail.component.css']
})
export class RestaurantDetailComponent implements OnInit {
id: Number;
sub: any;
@Input() restaurant: Restaurant;
constructor(private restaurantService: RestaurantService, private route: ActivatedRoute) { }
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
this.id = +params['id']; // (+) converts string 'id' to a number
});
this.restaurantService.getRestaurant(this.id).then(
res => this.restaurant = new Restaurant(res.id, res.restaurant_name, res.description
, res.phone, res.address, res.category));
}
}
文件:restaurant-detail.component.html
Restaurant detail page with Id: {{ id }}
<section>
Name: {{ restaurant['restaurant_name'] }}
</section>
文件:restaurant-service.ts
import { Injectable } from '@angular/core';
import { Http } from '@angular/http';
import { ActivatedRoute, Params } from '@angular/router';
import { Location } from '@angular/common';
import 'rxjs/add/operator/toPromise';
import { Restaurant } from './restaurant';
@Injectable()
export class RestaurantService {
private restaurantUrl = 'api/restaurant'; // URL to web API
constructor(private http: Http) { }
//Get all restaurants
getRestaurants(): Promise<Restaurant[]> {
return this.http.get(this.restaurantUrl)
.toPromise()
.then(response => response.json().
map(x => new Restaurant(x.id, x.restaurant_name, x.description, x.phone, x.address,
x.category)))
.catch(this.handleError);
}
getRestaurant(id: Number):Promise<Restaurant>{
return this.http.get(this.restaurantUrl + "/" + id)
.toPromise()
.then(response => response.json());
}
private handleError(error: any): Promise<any> {
console.error('Error', error);
return Promise.reject(error.message || error);
}
}
我使用 spring boot 作为我的后端来检索数据。目前它似乎有效,但我想知道为什么会出现此错误以及如何解决它,谢谢。
完整的 Github 代码:https://github.com/zhengye1/Eatr/tree/dev
【问题讨论】:
-
应该这样做 -
Name: {{ restaurant?.restaurant_name }}
标签: angular