【发布时间】:2019-03-19 18:19:16
【问题描述】:
错误
ServiceDetailComponent.html:3 错误类型错误:无法读取属性 未定义的“服务名称”;在 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 }}
【问题讨论】:
-
为了给您一个很好的答案,如果您还没有看过How to Ask,它可能会对我们有所帮助。如果您可以提供minimal reproducible example,它可能也很有用。
-
service.serviceName可能仅在您的服务中的 ajax 请求完成后才能工作。在此之前,这是 100% 确定它未定义
标签: angular typescript angular-ui-router