ERROR
ServiceDetailComponent.html:3 ERROR TypeError: Cannot read property 'serviceName' of undefined; at Object.eval [as updateRenderer] (ServiceDetailComponent.html:3); at Object.debugUpdateRenderer [as updateRenderer] (core.js:11080); at checkAndUpdateView (core.js:10456); at callViewAction (core.js:10692); at execComponentViewsAction (core.js:10634); at checkAndUpdateView (core.js:10457); at callViewAction (core.js:10692); at execEmbeddedViewsAction (core.js:10655); at checkAndUpdateView (core.js:10452); at callViewAction (core.js:10692);
Service :
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 );
}
}
Component
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 Result
<p>
service-detail works!
</p>
{{ service.serviceName }}
service.serviceName
might only work after the ajax request in your service has completed. Before that, that's 100% sure its undefined – ValLeNain