1

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 {} .

1

1 Answer 1

1

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)
    );
  }
Sign up to request clarification or add additional context in comments.

6 Comments

I am trying that but I can't use ` entreprise: Enterprise = {};` it gives an error I tried entreprise: Enterprise; but then I get an error on the HTML {{entreprise.name}} I also tried ` entreprise= Enterprise()` but I get undefined in the console.log
entreprise: Enterprise = {} will not work because you are trying to create an Enterprise object without any of the properties that we declared in the Enterprise class. If you want to be able to do this, you should change the Enterprise class into an interface and mark the properties as optional. Let me update my answer with this.
In my answer, I've updated the contents of both site.ts and enterprise.ts to make them interfaces with all optional attributes.
I'm still getting undefined on the log. the HTML code works {{entreprise.name}} but the back-end is not console.log(this.entreprise.name);
I see what you are trying to do. Let me add an update in my answer.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.