I am experiencing issues with my Angular2 project where not all of my component variables are being passed to the

My problem involves sending three variables to my HTML template, but it only recognizes one of them.

The HTML template I am using looks like this:

<div class="page-data">
    <form method="post" action="api/roles/edit/{{role?.ID}}" name="{{role?.ID}}">

        <table cellpadding="11">
            <tr>
                <div class="label"> Role Name </div>
                    <input type="text" name="role_name" value="{{role?.ROLE_NAME}}">
                <br>
                <br>
                <div class="label"> Description</div>
                    <input type="text" name="description" value="{{role?.DESCRIPTION}}">

                <br>
                <br>
                <div class="label" *ngIf="role?.ACTIVE_FLAG === 'Y'"> Active Record </div>
                    <input type="radio" name="active_flag" value="Y" checked> Active
                    <input type="radio" name="active_flag" value="N"> Inactive
                <div *ngIf="role?.ACTIVE_FLAG === 'N'">
                    <input type="radio" name="active_flag" value = "Y"> Active
                    <input type="radio" name="active_flag" value= "N" checked> Inactive
                </div>
                <br>
                <br>
            </tr>
        </table>

        <div class="label"> Active Modules</div>
        <select id="modules_applied" name="module_name">
            <option value="none"> None</option>
            <option *ngFor="#module of modules" value="{{module.MODULE_NAME}}">{{module.MODULE_NAME}}</option>
        </select>

        <div class="data-table">

            <table id="modules_table" border="1" cellpadding="7" cellspacing="7"></table>

            <br>
            <br>

        </div>
        <div class="label"> Inactive Modules </div>
        <select id="new_mods_select" name="new_modules">
            <option value="none"> None</option>
            <option *ngFor="#module of new_modules" value="{{module.MODULE_NAME}}">{{module.MODULE_NAME}}</option>
        </select>
        <div class="data-table">

            <table id="new_modules_table" border="1" cellpadding="7" cellspacing="7"></table>

            <br>
            <br>
        </div>
        <input type="submit" name="submit" value="Save">
    </form>
</div>

and The component file:

import {Component} from 'angular2/core';
import { CORE_DIRECTIVES } from 'angular2/common';
import {RoleService} from './../services/roles.services';
import {OnInit} from 'angular2/core';
import {Http, HTTP_PROVIDERS} from 'angular2/http';
import {RouteParams, RouterLink} from 'angular2/router';


@Component({
  selector: 'edit_role',
  providers: [RoleService],
  directives: [CORE_DIRECTIVES],
  templateUrl: 'app/roles/edit_role.html'
})
export class RoleEdit implements OnInit{

    role: any;
    modules: any;
    new_modules: any;
    params: any;

    constructor(private _roleService: RoleService, params:RouteParams){
        this.params = params.get('id');
    };

    ngOnInit(){
        this.getEditRoles(this.params);
    };

    getEditRoles(id){
        this._roleService.getEditRoles(id).subscribe(role_edit =>
            {this.role = role_edit.data[0],
            this.modules = role_edit.modules[0],
            this.new_modules = role_edit.new_modules[0]},
            error => {
                console.log('error logged:');
                console.log(error);
            }
        );
    };
}

The error message I received is:

Cannot find a differ supporting object '[object Object]' in [modules in RoleEdit@29:11]

I recently discovered the use of question marks for async calls with: {{role?.ID}}. It seems that ngFor loops do not work well with them, which might be the source of my issue. Thank you!

Edit:

Here is more of the code, including what is in my roles services and the JSON data I am working with.

The role.services file:

import {Injectable} from 'angular2/core';
import {Http, HTTP_PROVIDERS} from 'angular2/http';
import 'rxjs/Rx';

@Injectable()
export class RoleService {


    constructor(public http: Http) {

    }

    getRoles(){
        return this.http.get('http://localhost:3000/api/roles/')
            .map((response => response.json().data));
    }

    getEditRoles(id){
        return this.http.get('http://localhost:3000/api/roles/edit/' +id)
            .map((response => response.json()))
    }
}

And here is the JSON data I am trying to capture:

{
  new_modules: [
    {
      MODULE_NAME: "user_roles"
    }
  ],
  modules: [
     {
      ROLE_ID: 6,
      MODULE_NAME: "roles",
      INSERT_ALLOWED_FLAG: "Y",
      UPDATE_ALLOWED_FLAG: "N",
      DELETE_ALLOWED_FLAG: "N",
      QUERY_ONLY: "Y"
    },
    {
      ROLE_ID: 6,
      MODULE_NAME: "test_mod",
      INSERT_ALLOWED_FLAG: "Y",
      UPDATE_ALLOWED_FLAG: "N",
      DELETE_ALLOWED_FLAG: "N",
      QUERY_ONLY: "N"
    },
    {
      ROLE_ID: 6,
      MODULE_NAME: "users",
      INSERT_ALLOWED_FLAG: "Y",
      UPDATE_ALLOWED_FLAG: "Y",
      DELETE_ALLOWED_FLAG: "Y",
      QUERY_ONLY: "Y"
    }
  ],
 data: [
    {
      ID: 6,
      ROLE_NAME: "Fire",
      DESCRIPTION: "Something hot",
      ACTIVE_FLAG: "Y"
    }
  ]
}

Answer №1

When referencing and giving credit to this particular response, it seems that you might be overlooking the

.map(res => res.json())

for your Http request. Your code excerpts do not include the getEditRoles function in the RoleService, so I cannot definitively say if this part is indeed missing. However, my suspicion is that after making the Http request, you need to ensure it is properly returned. The method in question should look something like this for it to function correctly:

public getEditRoles(id: number): Observable<any>{
    return this.http.get('some.url', {id: id})
               .map(res => res.json());
}

This will convert the Response object from the Http call into JSON format for usage in your component.

Update

Upon reviewing your updated question, I noticed some inconsistencies in your code. In your component, there is a line that reads

this.modules = role_edit.modules[0]

This line implies that you are assigning the value of the first object in the modules array as a whole to the array modules.

Therefore, at present, this.modules would hold the following value:

{
  ROLE_ID: 6,
  MODULE_NAME: "roles",
  INSERT_ALLOWED_FLAG: "Y",
  UPDATE_ALLOWED_FLAG: "N",
  DELETE_ALLOWED_FLAG: "N",
  QUERY_ONLY: "Y"
}

Subsequently, when you attempt to iterate over it, the framework encounters errors as it is not an array.

To address this issue and achieve the desired functionality, modify

this.modules = role_edit.modules[0]

to

this.modules = role_edit.modules

This adjustment will assign the entire array to this.modules rather than just the initial item.

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

Enable the use of empty spaces in ag-grid filter bars

I'm experiencing an issue with the ag grid filter. It seems to be disregarding white spaces. Is there a way to configure the grid to recognize blank spaces in the filter? Any suggestions for resolving this issue? Where can I find the option to accept ...

Determining the type of a single deconstructed variable from an object

My useForm hook is designed to take an object and return several useful functions back, including that object as a state. However, due to TypeScript limitations, the specific type from the initial object cannot be returned because useForm accepts dynamic o ...

Issue with Displaying Local Server Image in Angular 2 HTML

I am facing an issue with my Angular 2 Application. It retrieves items from a local database where the server stores the image of the item and the database stores the path to that image stored on the server. While I can retrieve all the items without any p ...

Building secure authentication with Angular, node.js, and an identity provider through SAML integration

Implementing SSO using SAML2 is my goal, but I am facing a challenge with a distributed system where each instance operates independently on its server. There are three instances in the environment: Instance #1: an angular frontend Instance #2: a node.js ...

The functioning of the Angular4 website is currently experiencing issues

Recently, I made the switch from Angular2 to Angular4 on my website. When running 'ng serve', everything works perfectly fine except for a warning about a deprecated template that should be changed to 'ng-template'. I use ng-bootstrap a ...

What steps should be taken when encountering an error with fs while using ANTLR?

I have encountered an issue with antlr while using Angular in Visual Studio Code. I am familiar with including and writing a grammar in a project, but recently I ran into a problem when starting it: "ERROR in ./node_modules/antlr4/CharStreams.js Module no ...

Unable to locate module '...' or its associated type declarations. Issue encountered in NextJS with TypeScript integration

Within my NextJs project, I have generated a cookie.ts file in the utils directory. Upon running "npm run dev" and accessing my application on localhost:3000, everything runs smoothly with no errors, and the code in my utils/cookie.ts file is retrieved suc ...

Navigating through nested routes in Angular 5

I recently started learning about Angular, and I could really use some guidance on routing. Here is my current setup. app.component.html <router-outlet name="nav"></router-outlet> <router-outlet name="left-sidebar"></router-outlet> ...

agm-circle has such a high drag sensitivity in angular 4

I have implemented an agm-circle in an agm-map within Angular 4. Everything is working as expected, however, I am experiencing an issue with the speed at which the circle moves when dragged. Is there a way to slow down this movement? Below is my code sni ...

Unable to display animation without first launching it on Rive web

I attempted to incorporate a Rive animation into my Angular web application <canvas riv="checkmark_icon" width="500" height="500"> <riv-animation name="idle" [play]="animate" (load)=&qu ...

Employing 'as' in a similar manner to *ngIf

Utilizing the *ngIf directive, one can simplify code by assigning a property from an observable using syntax like *ngIf = (value$ | async).property as prop . This allows for the use of prop throughout the code without repeated references to (value$ | async ...

Passing an array from a parent component to a child component in Angular

Just to give you some background, I only started my Angular learning journey about a week ago, so feel free to start from the very beginning. So, how can this be achieved? Inside app.component.ts, there is a standard array that needs to be accessible by m ...

Using the RxJS iif operator for implementing multiple condition statements

What is the optimal approach for returning Observables based on multiple conditions? This is my current code implementation: iif( () => !this.id, this.service.listStuff$(), this.service.listStuffById$(this.id) ).pipe( switchMap((list: L ...

Unveiling the mysteries of abstract classes in TypeScript

I have a collection of different animal classes, all derived from a common abstract base class. To illustrate: abstract class Animal { abstract speak(): string; } class Dog extends Animal { speak(): string { return "woof... sigh" } } ...

Is it possible to pass a parameter to an NGXS action that is not the Payload?

I am working on implementing an Ngxs action that includes a parameter in addition to the payload. This parameter is used to determine whether or not a notification should be sent. @Action(UpdateUser) async UpdateUser( ctx: StateContext<ProfileStat ...

Storing Array Data in Ionic Using Native Storage - A Step-by-Step Guide

I want to implement a feature in my app where I can store translation history using Ionic Native Storage. Every time a word is translated, the translation action (date, translated word) will be saved in the storage. Then, when I navigate to the history pag ...

Executing two different types of tests with Angular CLI can be done by utilizing the `ng test

My testing setup includes two distinct types of tests: Unit tests (created as standard angular cli .spec.ts files) Functional tests (developed as my specific .func.spec.ts files, following the same structure as .spec.ts files but interacting with real da ...

Can someone help me create Three.js types using the frontend option I choose?

I'm currently developing a user-friendly browser application for editing shaders in three.js using react-three-fiber. I want to enhance the functionality by allowing users to add additional uniforms to the ShaderMaterial. However, I do not want to exp ...

What is the process for changing the src property to a URL that is outside of the project

Currently, I am developing a project using Ionic. My goal is to include a variable that holds the URL of an image in an image tag. <div *ngFor="let item of imagearr"> <img [src]="item.image.URL"> Unfortunately, when I attempted this method, i ...

Angular2-starter configuration setup with environment-based variables (such as .env or .conf) for testing and production settings

Frameworks like PHP Laravel often include files for local configuration, separate from dev, test, and production environments. How can a configuration file be provided for an angular-starter project that contains all local environment variable values (su ...