Reputation: 151
I have an angular page which has a list of properties. Each property has a link to view the details of the property. I have a function which maps the property by id, however as a return I am always getting undefined (printed in console).
service.ts
getProperties(): Observable<IProperty[]>{
return this.http.get<IProperty>('http://localhost:3000/')
.do(data => this.properties.push(JSON.stringify(data)))
.catch(this.handleError);
}
getProperty(id:number): Observable<IProperty>{
return this.getProperties()
.map((properties: IProperty[])=> properties.find(p=>p.propertyId===id));
}
propertyDetail.component.ts
import { Component, OnInit } from '@angular/core';
import { IProperty } from './property';
import { ActivatedRoute, Router } from '@angular/router';
import { ApiService} from '../api/api.service';
import { PropertyGuardService } from './property-guard.service'
@Component
({
selector: 'propertyDetail',
templateUrl: './propertyDetail.component.html',
providers: [PropertyGuardService]
})
export class PropertyDetailComponent implements OnInit
{
pageTitle:string = "Property Details";
property: IProperty;
errorMessage: string ="";
constructor(private _route : ActivatedRoute,
private _router: Router,
private apiService: ApiService){
console.log(this._route.snapshot.paramMap.get('id'));
}
ngOnInit(){
const param = this._route.snapshot.paramMap.get('id');
if(param){
const id = +param;
this.getProperty(id);
console.log(this.getProperty(id));
}
}
getProperty(id:number)
{
this.apiService.getProperty(id).subscribe(
property => this.property = property,
error => this.errorMessage = <any>error);
}
onBack(): void
{
this._router.navigate(['/properties']);
}
}
Upvotes: 2
Views: 678
Reputation: 2675
You set one property using property => this.property = property
by subscribe in the suitable time and now you can use this.property
in the view like {{property?.id}}
.
If you want to check Property
whether being fetched properly or not on the console, you can use as follows:
getProperty(id:number){
this.apiService.getProperty(id).subscribe(
property => {
this.property = property,
console.log(property) // check property returned here
});
}
Upvotes: 1