Troubleshooting: Issue with binding drop down using Angular 2 and Node JS in Mean Stack

Currently, I am utilizing MEAN (MongoDB Express Angular Node) to connect my dropdown in angular 2 with MongoDB values in the backend.

In my node JS, I have defined routes and models as shown below:

\var\www\html\Express\nodeauthapp-master\routes\categories.js

//Get all categories
router.get('/get',(req,res,next) => {
    //res.send('Get categories');
    Categories.getAllCategories((err,categories)=>{
    if(err)
    {
      res.json({success: false, msg:'Failed to get categories'});
    } 
    else
    {
      res.json({success: true, mainCategories:categories});
    }
  }); 
})

\var\www\html\Express\nodeauthapp-master\models\categories.js

// Categories Schema
const CategoriesSchema = mongoose.Schema({

category_name: {
    type: String,
    required: true
}

});

const Categories = module.exports = mongoose.model('Categories', CategoriesSchema);

//Get all categories
module.exports.getAllCategories = function(callback){
Categories.find({},callback)
}

For binding the dropdown in Angular 2, I use the following method:

blank-page.component.html

<form role="form">
<fieldset class="form-group">
<label>Select Category</label><br/><br/>
<select [(ngModel)]="selectedObject" name="selectedObject" class="form-control">
<option disabled>--Select--</option>

<option *ngFor="let category of categories" [value]="category">{{category}}</option>
</select>
</fieldset>
</form>

blank-page.component.ts

export class BlankPageComponent implements OnInit {

category:String;
public categories: Array<any> = [];

constructor(private addproductService: AddproductService,
            private flashMessage: FlashMessagesService,
            private router: Router) { }

ngOnInit() {
   const category = {
       categories: this.category

}

console.log(category);

this.addproductService.loadData(category).subscribe(data => { 
  if(data.success){
    this.categories = data.mainCategories;
    console.log('Dropdown bound successfully');
} else {
    console.log('Not bound');
}
});

}

addproduct.service.ts

export class AddproductService {

category: any;
loadData(category) {

let headers = new Headers();
headers.append('Content-Type', 'application/json');
return this.http.get('http://10.*.*.*:3000/categories/get', { headers: headers })
.map(res => res.json());

}
}

The console log shows that the dropdown is successfully bound, however, in the frontend, no values are being bound.

When I access the GET API URL in Postman, I can see the list of categories.

In the browser logs, I receive: Object {categories: undefined}

My object contains: https://i.stack.imgur.com/lWhWW.jpg

Answer №1

Try updating your HTML code like so:

<form role="form">
    <fieldset class="form-group">
            <label>Choose a Category</label><br/><br/>
                <select [(ngModel)]="selectedObject" name="selectedObject" class="form-control">
                    <option disabled>--Select--</option>

                    <option *ngFor="let category of categories" [value]="category.category_name">{{category.category_name}}</option>
                </select>
        </fieldset>
</form>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Experiencing SyntaxError when utilizing rewire and mocha for Node.js testing. Unexpected token encountered

Trying to test a function exported from a nodejs file, I am utilizing q to manage promises. The function returns a promise that is either resolved or rejected internally through a callback. Within this callback, another function from a different location i ...

Successfully launched Express app on Vercel, with only the landing page functioning and other routes still under development

My Node Express server side has been deployed to Vercel, but I am encountering an issue. The landing page always works fine, however, other routes like `/users` or any others only work the first time. After that, even though the landing page still works, t ...

How can I verify if the first character is a letter using express-validator?

case 'username': { return [ check( 'content.data.username', 'Username must contain at least one letter' ) // .matches('(?=.*[a-z])(?=.*[0-9])&apo ...

Error encountered while trying to establish connection using ODBC driver connection string

I've been searching for an answer to this general question but can't seem to find one. I'm currently utilizing a node module called https://www.npmjs.com/package/odbc The module instructs me to install an ODBC driver for the specific databa ...

Retrieve data from Last.fm API by utilizing both Node.js and Angular framework

I am currently working on implementing the node-lastfmapi track.search method into my project. I have successfully retrieved the results, but I am facing challenges in integrating them into the front end using Angular. My backend is powered by mongoDB and ...

Running "vue ui" with Node.js v17.2.0 - A step-by-step guide

After updating to Node.js v17.2.0, I am facing issues with running "vue ui" in my project. The error message I receive indicates a problem with node modules: at Object.readdirSync (node:fs:1390:3) at exports.readdir (/usr/local/lib/node_modules/@vu ...

Issue: angular2-cookies/core.js file could not be found in my Angular2 ASP.NET Core application

After spending 2 hours searching for the source of my error, I have decided to seek help here. The error message I am encountering is: "angular2-cookies/core.js not found" I have already installed angular2-cookie correctly using npm. Below is the code ...

Error encountered while configuring the log4js function in a NodeJs environment

Encountering an issue with my NodeJs application where I'm using log4js for logging. The error in the console window is related to a syntax problem while running in the express runtime platform. Error: undefined:1 ?{ ^ SyntaxError: Unexpected token ...

Tips for preserving the Mobile Stepper's current state when the next button is clicked

To maintain the progress state of the Mobile Stepper, even when a user logs out and logs back in, it is crucial to save the current position. The goal is for the user to resume from where they left off, such as at 2% completion instead of starting over at ...

I am experiencing difficulties with socket.io and my Flutter app is unable to establish a connection with the server or backend component

For the backend of my flutter app, I utilized socket.io and node.js. I created an index.json file and implemented a function on a page to establish a connection between my app and the backend. However, I am facing issues with it not working as expected. Be ...

Exploring the Connection Between Express.js and CORS

I developed a frontend using react.js and an API server using express.js. To handle CORS, I utilized the cors package as shown below: var passport = require("passport"); const express = require('express'); const cors = require('cor ...

Tips for concealing API endpoints in a React Native Android application

I've developed a nodejs, express, and mongodb API that is currently hosted on Heroku. My next step is to utilize this API URL within my React Native Android app. Unfortunately, I'm facing an issue where the API URL could potentially be exposed to ...

Enable users to designate custom methods as either asynchronous or synchronous

These are my TypeScript method signatures: onPinnedError?(info: HavenInfo, req: Request, res: Response): HookReturnType; async onPinnedError?(info: HavenInfo, req: Request, res: Response): HookReturnType; onPinnedUnhandledRejection?(info: HavenInfo, ...

The body parser is preventing the NODE from loading on localhost

var express = require('express'); var app = express(); var bodyParser = require('body-parser'); //ISSUE LINE **app.use(parser.json);** /////////////// var todos = []; var nextTodoItem = 1; app.use(bodyParser.json); ap ...

Executing multiple instances of a Firebase cloud function

I am working with a Firebase (Google) cloud function that is structured like this // Initialize the Auth0 client var AuthenticationClient = require('auth0').AuthenticationClient; var auth0 = new AuthenticationClient({ domain: 'fam ...

Using node.js to download files with axios, streaming the content, and then

I am attempting to download a PDF file using axios, and save it on the server side using fs.writeFile. My code is as follows: axios.get('https://xxx/my.pdf', {responseType: 'blob'}).then(response => { fs.writeFile('/temp/my ...

Tips for troubleshooting or modifying a dependency that exclusively consists of type declaration files

I am currently facing a challenge where I need to access and debug/change the code of one of our dependencies that contains custom Angular components from a separate repository. This particular repository is being included via a self-hosted npm registry wi ...

Developing with TypeScript - Utilizing the <reference path="....."> directive

Recently, I encountered an issue while adding a plugin to the TypeScript compiler. After including my code and compiling tsc.ts, it compiled without any errors. However, when I attempted to run it, I noticed that some variables declared in io.ts were missi ...

Upon opening the terminal, Vim's Ex mode is activated

Recently, I stumbled upon an issue with Vim in my Mac terminal. While copy and pasting text the other day, I accidentally triggered something that now causes Vim to load in Ex mode every time I open the Terminal. I am aware of how to exit Ex mode once insi ...

What is the best way to access and modify file information in nodejs?

I'm looking to retrieve and modify the details of a .mp4 file, specifically the Description property (Title, Subtitle, Rating, Tags, Comments). Is there a way to do this using Node.js? I understand that typically you would right-mouse click on the fil ...