错误
ServiceDetailComponent.html:3错误TypeError:无法读取属性 'serviceName'未定义;在Object.eval [作为updateRenderer] (ServiceDetailComponent.html:3);在Object.debugUpdateRenderer [as updateRenderer](core.js:11080);在checkAndUpdateView (core.js:10456);在callViewAction(core.js:10692);在 execComponentViewsAction(core.js:10634);在checkAndUpdateView (core.js:10457);在callViewAction(core.js:10692);在 execEmbeddedViewsAction(core.js:10655);在checkAndUpdateView (core.js:10452);在callViewAction(core.js:10692);
服务:
import { IServices } from './../../services';
import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';
@Injectable({
providedIn: 'root'
})
export class ServiceService {
// private _url: string = 'https://api.myjson.com/bins/1d8suw';
private _url: string = 'https://api.myjson.com/bins/1azcrc';
constructor(private http: HttpClient) { }
getServices(): Observable<IServices[]> {
return this.http.get<IServices[]>(this._url);
}
getService(id: number) {
return this.http.get<IServices[]>(this._url + id );
}
}
组件
import { Component, OnInit } from '@angular/core';
import { ServiceService } from '../services/service.service';
import { ActivatedRoute, Router } from '@angular/router';
import { IServices } from 'src/app/services';
@Component({
selector: 'app-service-detail',
templateUrl: './service-detail.component.html',
styleUrls: ['./service-detail.component.css']
})
export class ServiceDetailComponent implements OnInit {
id: number;
service: IServices[];
constructor(private serviceService: ServiceService,
private route: ActivatedRoute
) { }
ngOnInit() {
this.id = this.route.snapshot.params['id'];
this.serviceService.getService(this.id)
.subscribe(service => {
this.service = service;
});
}
}
HTML结果
<p>
service-detail works!
</p>
{{ service.serviceName }}
答案 0 :(得分:0)
由于没有在undefined
中初始化service
属性,所以出现ServiceDetailComponent
错误。您可以在回调函数中对其进行初始化,该回调函数在服务器返回响应时异步运行。
检查是否为空或使用以下可选语法:
{{ service?.serviceName }}
答案 1 :(得分:0)
service: IService[]
->您期望获得服务列表,因此将其列为services: IService[]
。this.services
属性将是未定义的。如果要在模板中使用它,则应使用elvis
运算符-这是?
的漂亮名称,看起来像这样:service?.serviceName
。本质上,这告诉Angular在service
未定义的情况下不要抛出错误,并在可用时重新呈现该值。由于this.services
是一个数组,因此您需要使用*ngFor
结构指令遍历所有项目:
<p *ngFor="let service of services">
{{service.serviceName}}
</p>
如您所见-我在这里没有使用elvis
运算符,因为除非初始化*ngFor
值,否则services
不会呈现任何内容。
答案 2 :(得分:-1)
service:IServices [];您正在尝试访问“服务”数组的属性。 引用数组中的项目,然后引用属性。