angular 2 Array as" undefined"

时间:2017-02-08 18:55:31

标签: angular

情况就是这样。

我正在尝试从我的数据库中获取一个数字,但每次我将数字放入Array()时,都表示未定义。

我可以获取数字,因为我可以在我的HTML中显示它但在数组内部不起作用。

知道为什么会这样吗?



import { Component,  OnInit } from '@angular/core';
import { DomSanitizer, SafeResourceUrl, SafeUrl, SafeHtml } from '@angular/platform-browser';
import { ActivatedRoute } from '@angular/router';
import { RealEstatePhotography } from '../real-estate-photography';
import { RealEstatePhotographyService } from '../real-estate-photography.service';

@Component({
  selector: 'app-real-estate-photography-detail',
  templateUrl: './real-estate-photography-detail.component.html',
  styleUrls: ['./real-estate-photography-detail.component.css'],
  providers: [RealEstatePhotographyService],
})

export class RealEstatePhotographyDetailComponent implements OnInit {


realEstate;
amount
photos = Array(this.amount)

  constructor(private route: ActivatedRoute, private _realEstatePhotographyService: RealEstatePhotographyService, private sanitizer: DomSanitizer) {}


  ngOnInit(){
    this.route.params.subscribe(params => {
      let title = params['title'];
      let realEstate = this._realEstatePhotographyService.getItem(title).subscribe(realEstate => {
        this.realEstate = realEstate;
        this.amount = this.realEstate.amount

      });

    });
}

}




1 个答案:

答案 0 :(得分:0)

当时未定义金额。您需要每次都更新photos

export class RealEstatePhotographyDetailComponent implements OnInit {


realEstate;
amount: Number;
photos: Photo[] = [];

  constructor(private route: ActivatedRoute, private _realEstatePhotographyService: RealEstatePhotographyService, private sanitizer: DomSanitizer) {}


  ngOnInit(){
    this.route.params.subscribe(params => {
      let title = params['title'];
      let realEstate = this._realEstatePhotographyService.getItem(title).subscribe(realEstate => {
        this.realEstate = realEstate;
        this.amount = this.realEstate.amount;
        this.photos.push(realEstate.photo);
      });

    });
}

编辑:

刚才意识到你可能正在尝试定义数组的大小 - 没有必要在javascript中这样做。只需将其声明为空数组,然后根据需要推送照片。