【问题标题】:Chrome complaining "restaurant_name" is not defined, but in the page it actually display the valueChrome 抱怨“restaurant_name”未定义,但在页面中它实际上显示了该值
【发布时间】: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


【解决方案1】:

尝试使用*ngIf 如下更改 restaurant-detail.component.html

<section *ngIf="restaurant">
   Name: {{ restaurant['restaurant_name'] }}
</section>

它在控制台中打印的原因可能是餐厅未定义。添加*ngIf 只会在将值分配给餐厅变量后呈现视图。

额外: 在分配或加载该数据之前,您可以添加加载程序。 如果您使用 angular 4,请查看 *ngIf else as well。 否则,您也可以编写自己的 else。

【讨论】:

  • 似乎工作。但是为什么我这样做,Chrome 会抱怨呢?
  • @VincentZheng 这是因为在服务/服务器调用之后分配变量/输入餐厅的数据之前渲染模板时。在那之前它是未定义的。因此,当浏览器现在必须显示未定义变量的值时,就会弹出错误。这是否有助于您理解或需要更多帮助?
【解决方案2】:

这是初始渲染的抱怨原因,此值未定义,仅在请求后显示。

要修复它,设置餐厅的初始值。

@Input() restaurant: Restaurant = {};

但是你没有通过餐厅,所以你可以不输入就直接写

restaurant: Restaurant = {}; or new Restarurant depends on object.

或者最后一个只是使用?在模板中会告诉 Angular 这个值可以是未定义的。

   Name: {{ restaurant?.restaurant_name }}

【讨论】:

    猜你喜欢
    • 2014-09-03
    • 2013-01-03
    • 2020-07-10
    • 2015-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-17
    相关资源
    最近更新 更多