AngularJS上的Observable没有插值:"无法找到未定义的属性"

时间:2017-07-28 03:22:31

标签: angularjs typescript data-binding interpolation observable

大家。我有一个显示猫的应用程序。它只是使用服务和http从JSON获取数据。我能做的很多,而且很有效。但是,我还有一个特色是猫的细节"页面,涉及路由。它使用相同的服务,但它不呈现整个JSON文件,而只呈现特定对象,在本例中为特定的cat。我使用find()方法在第一个getcat()函数中搜索所述特定的cat,使用route.params值作为搜索参数。

但是,路由不是问题本身。如下所示。我的控制台可以打印get函数的返回并正确显示它应该的唯一对象。问题似乎与插值的时刻有关。当我绑定变量,从组件到模板,它应该携带可观察数据时,Angular会向我显示一个"无法读取属性' Nombre'未定义"。

我真的不知道为什么这不起作用。有些人建议在绑定上使用安全导航操作符,但这对我来说并不是这样。同样的错误不断出现。

我已经重新检查了不同日期的语法,我相信我做对了。这让我觉得问题依赖于与组件范围有关的东西,可能与生命周期钩子有关。

任何帮助将不胜感激。

这是我的JSON

[
  {
    "Nombre": "Xiomara",
    "Edad": "1",
    "Raza": "Criolla",
    "Color": "Café",
    "Vacunacion": "Todas",
    "Estado": "Esperando",
    "Foto" :"-104827/"
  },
  {
    "Nombre": "Deneb",
    "Edad": "4",
    "Raza": "Siamés",
    "Color": "Negro",
    "Vacunacion": "Falta",
    "Estado": "Esperando",
    "Foto" : ""
  {
    "Nombre": "Pilatos",
    "Edad": "2",
    "Raza": "Dragoon",
    "Color": "Pardo",
    "Vacunacion": "Azul",
    "Estado": "Todas",
    "Foto" : ""
  },
  {
    "Nombre": "Ulysses",
    "Edad": "1",
    "Raza": "Criollo",
    "Color": "Gris",
    "Vacunacion": "Falta",
    "Estado": "Esperando",
    "Foto" : "rt-fur-cat-104827/"
  },
  {
    "Nombre": "Raiku",
    "Edad": "1",
    "Raza": "Pokemon",
    "Color": "Rayas blancas",
    "Vacunacion": "Todas",
    "Estado": "Esperando",
    "Foto" : "http-white-short-fur-cat-104827/"
  }
]

这是我的service.ts

@Injectable()
export class GatosService {
  private _productUrl ='./Lista Gatos.json';

  constructor(private _http: Http) { }

  getGatos(): Observable<IGato[]> {
    return this._http.get(this._productUrl)
      .map((response: Response) => <IGato[]>response.json())
      .do(data => console.log('All: ' + JSON.stringify(data)))
      .catch(this.handleError);
  }

  /* Searches array objects to match the id*/
  getGato(id: string): Observable<IGato> {
    return this.getGatos()
      .map((gatos: IGato[]) => gatos.find(p => p.Nombre === id))
      .do(data => console.log('Gato individual: ' + JSON.stringify(data))); 
    /*prints individual object on console. It does work */
  }

  private handleError(error: Response) {
   console.error(error);
   return Observable.throw(error.json().error || 'Server error');
  }
}

这是我的detailComponent.ts

export class GatoDetalleComponent implements OnInit {
  pageTitle: string = 'gato detalle';
  gato: IGato;
  errorMessage: string;
  private sub: Subscription;

  constructor(
    private _route:ActivatedRoute,
    private _gatosService: GatosService
  ) {
    console.log(this._route.snapshot.params['id']) /* prints id so i know it works */
  }

  ngOnInit(): void {
    /* Calls the service function using the route.params as argument */
    this.sub = this._route.params.subscribe(
      params => {
        let id = params['id'];
        this.getGato(id);
      }
    )
  }
  /* Subscribes to the service getGato function and assigns it to variable gato*/
  getGato(id: string) {
    this._gatosService.getGato(id).subscribe(
      product => this.gato = product,
      error => this.errorMessage = <any>error);

  }
}

这是我的详细信息component.html

<table>
  <tr><span class="visor-propiedad"> Nombre: </span><span class="visor-valor">{{gato.Nombre}}</span></tr>
  <tr><span class="visor-propiedad">Edad: </span><span class="visor-valor">{{gato.Edad}}</span></tr>
  <tr><span class="visor-propiedad">Raza: </span><span class="visor-valor">{{gato.Raza}}</span></tr>
  <tr><span class="visor-propiedad">Color: </span><span class="visor-valor">{{gato.Color}}</span></tr>
  <tr><span class="visor-propiedad">Vacunacion: </span><span class="visor-valor">{{gato.Vacunacion}}</span></tr>
  <tr><span class="detalle" [routerLink]="['/lafamilia', gato.Nombre]">Conóceme!</span></tr>
</table>

这是我的浏览器控制台上显示的错误

 EXCEPTION: Uncaught (in promise): Error: Error in ./GatoDetalleComponent class GatoDetalleComponent - inline template:13:38 caused by: Cannot read property 'Nombre' of undefined
    Error: Error in ./GatoDetalleComponent class GatoDetalleComponent - inline template:13:38 caused by: Cannot read property 'Nombre' of undefined

浏览器控制台会打印我想要的对象。问题是我认为是插值问题。

gato.service.ts:27 Gato individual: {"Nombre":"Xiomara","Edad":"1","Raza":"Criolla","Color":"Café","Vacunacion":"Todas","Estado":"Esperando","Foto":"https://www.pexels.com/photo/grey-and-white-short-fur-cat-104827/"}

1 个答案:

答案 0 :(得分:0)

问题是您的html代码在将值分配给gato之前正在执行。在插值中添加? befor goto,如下所示:

<table>
<tr><span class="visor-propiedad"> Nombre: </span><span class="visor-valor">{{gato?.Nombre}}</span></tr>
<tr><span class="visor-propiedad">Edad: </span><span class="visor-valor">{{gato?.Edad}}</span></tr>
<tr><span class="visor-propiedad">Raza: </span><span class="visor-valor">{{gato?.Raza}}</span></tr>
<tr><span class="visor-propiedad">Color: </span><span class="visor-valor">{{gato?.Color}}</span></tr>
<tr><span class="visor-propiedad">Vacunacion: </span><span class="visor-valor">{{gato?.Vacunacion}}</span></tr>
<tr><span class="detalle" [routerLink]="['/lafamilia', gato?.Nombre]">Conóceme!</span></tr>
</table>