简体   繁体   English

angular 2数组的名称为“ undefined”

[英]angular 2 Array comes as “undefined”

Here is the situation. 这是情况。

I am trying to get a number from my database but every time I put the number into the Array(), it says undefined. 我试图从数据库中获取一个数字,但是每次我将该数字放入Array()时,它都表示未定义。

I am able to get the number as I can display it in my HTML but inside the array, does not work. 我可以获取该数字,因为可以在HTML中显示该数字,但是无法在数组中使用它。

any idea why this is happening? 知道为什么会这样吗?

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

Amount is not defined at that time. 当时尚未定义金额。 You need to update photos every time. 您需要每次更新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);
      });

    });
}

EDIT: 编辑:

Just realized that you're probably trying to define the size of the array -- there's no need to do that in javascript. 刚意识到您可能正在尝试定义数组的大小-无需在javascript中进行操作。 Just declare it as an empty array and push in your photos as needed. 只需将其声明为空数组,然后根据需要放入您的照片即可。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM