如何从TypeScript访问对象属性?

时间:2017-06-07 23:11:36

标签: javascript angular typescript

我是Angular和TypeScript的新手,刚开始使用MEAN堆栈(MongoDB,Express,Angular,Node.js)处理项目。

我创建了这个猫鼬模块:

import * as mongoose from 'mongoose';

var Schema = mongoose.Schema;
const entrepriseSchema = new mongoose.Schema({
  name: {type: String, unique: true, required : true},
  telephone: Number,
  logo: String,
  web_site: String,
  sites: [
    {site_id: {type: Schema.Types.ObjectId, ref: 'Site'}}
  ]
});

const Entreprise = mongoose.model('Entreprise', entrepriseSchema);

export default Entreprise;

这是我的entreprise.component.ts:

import { Component, OnInit } from '@angular/core';
import { Http } from '@angular/http';
import { FormGroup, FormControl, Validators, FormBuilder } from '@angular/forms';
import { ActivatedRoute } from '@angular/router';

import { EntrepriseService } from '../services/entreprise.service';
import { SiteService } from '../services/site.service';


@Component({
  selector: 'app-entreprise',
  templateUrl: './entreprise.component.html',
  styleUrls: ['./entreprise.component.scss'],
  providers: [EntrepriseService, SiteService]
})
export class EntrepriseComponent implements OnInit {


  entreprise = {};
  sites = [];
  id: String;

  constructor(private entrepriseService: EntrepriseService,
              private siteService: SiteService,
              private http: Http,
              private route: ActivatedRoute) {
    this.id = route.snapshot.params['id'];
  }

  ngOnInit() {
    this.getEntrepriseById(this.id);
    //not working
    //console.log(this.entreprise.name);
    //console.log(this.entreprise.sites);
    //this.getSitesIn(this.entreprise.sites);
  }

  getEntrepriseById(id) {
    this.entrepriseService.getEntreprise(id).subscribe(
      data => this.entreprise = data,
      error => console.log(error)
    );
  }

  getSitesIn(ids) {
    this.siteService.getSitesIn(ids).subscribe(
      data => this.sites = data,
      error => console.log(error)
    );
  }
}

当我尝试显示从entreprise.component.html返回的属性时,它工作正常并显示所有属性:

  <h3>{{entreprise.name}}</h3>
       <div *ngFor="let site of entreprise.sites">
         {{site.site_id}}
       </div>
         {{entreprise.logo}}
         {{entreprise.web_site}}

但是如何在TypeScript端访问相同的属性? EntrepriseComponent中的注释代码是我尝试完成的,但由于this.entreprise类型为{},因此无效。

1 个答案:

答案 0 :(得分:1)

您在Node.js中的Mongoose中创建的Enterprise模型/架构位于服务器端。如果您希望UI上的TypeScript代码能够识别Enterprise中的属性,则必须在角度代码库中创建一个类。

在与models文件夹相同的级别创建一个名为services的文件夹。 (可选)

在上一步创建的models文件夹中创建两个名为site.ts和enterprise.ts的文件(如果需要,可以将这些文件放在不同的位置),其中包含以下内容:

<强> site.ts

export interface Site {
 site_id?: string;
}

<强> enterprise.ts

import { Site } from './site';
export interface Enterprise {
 name?: string;
 telephone?: string;
 logo?: string;
 web_site?: string;
 sites?: Site[];
}

现在,在EntrepriseComponent文件中添加以下导入

import { Enterprise} from '../models/entreprise';
import { Site } from '../models/site';

EntrepriseComponent文件中的第一行更改为

export class EntrepriseComponent implements OnInit {

  entreprise: Enterprise = {};
  sites: Site[] = [];

现在,enterprise属性的类型为Enterprise,您将能够访问我们在enterprise.ts文件中声明的属性。

<强>更新 另外,在console.log(this.enterprise.name)功能this.getEntrepriseById(this.id);之后,您不能ngOnInit()。这是因为当您尝试将其记录到控制台时,您获取企业对象的Web服务将无法解决。

如果要在控制台中查看企业对象,或者想要在服务调用解决后运行一些需要运行的代码并且this.enterprise对象具有值,那么最好的地方就是是你的getEntrepriseById功能。将getEntrepriseById功能更改为

  getEntrepriseById(id) {
    this.entrepriseService.getEntreprise(id).subscribe(
      data => {
           this.enterprise = data;
           console.log(this.enterprise.name);
           // Any code to run after this.enterprise resolves can go here.
      },
      error => console.log(error)
    );
  }