Angular - map始终返回undefined

时间:2018-01-07 10:15:31

标签: javascript angular

我有一个包含属性列表的角度页面。每家酒店都有一个链接,可以查看酒店的详细信息。我有一个函数,它通过id映射属性,但作为一个返回我总是未定义(在控制台中打印)。

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']);
    }
}  

1 个答案:

答案 0 :(得分:1)

您可以在适当的时间通过订阅使用property => this.property = property设置一个属性,现在您可以在this.property等视图中使用{{property?.id}}

如果要在控制台上检查Property是否正确提取,可以按如下方式使用:

getProperty(id:number){
   this.apiService.getProperty(id).subscribe(
      property => {
        this.property = property,
        console.log(property) // check property returned here           
      });
}