Ali
Ali

Reputation: 115

how to access object properties from TypeScript?

I'm new to Angular and TypeScript and just started working on a project using MEAN stack (MongoDB, Express, Angular, Node.js).

I created this mongoose module :

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;

and this is my 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)
    );
  }
}

when I try to display the properties of the returned from entreprise.component.html it works fine and displays all the properties :

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

but how can I access the same properties on the TypeScript side ? The commented code in the EntrepriseComponent is what I'm trying to accomplish but it's not working since this.entreprise is type {} .

Upvotes: 1

Views: 9581

Answers (1)

CodeWarrior
CodeWarrior

Reputation: 2851

The Enterprise model/schema that you created in Mongoose in Node.js resides on the server side. If you want the TypeScript code on the UI to recognize the properties in Enterprise, you will have to create a class in your angular codebase.

Create a folder named, say, models at the same level as your services folder. (Optional)

Create two files named site.ts and enterprise.ts in the models folder created in the previous step (You can put these file at a different location if you want) with the following contents:

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[];
}

Now, inside the EntrepriseComponent file, add the following imports

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

And change the first lines inside the EntrepriseComponent file to

export class EntrepriseComponent implements OnInit {

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

Now, the enterprise attribute will be of type Enterprise and you will be able to access the properties that we declared in the enterprise.ts file.

Update: Also, you cannot console.log(this.enterprise.name) immediately after this.getEntrepriseById(this.id); in your ngOnInit() function. This is because the web service you are making to get the enterprise object would not have resolved when you are trying to log it to the console.

If you want to see the enterprise object in the console or you want to run some code that needs to run after the service call has resolved and the this.enterprise object has a value, the best place to do this would be your getEntrepriseById function. Change the getEntrepriseById function to

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

Upvotes: 1

Related Questions