Having trouble locating a supporting object '[object Object]' of type while using Angular 2

As a newcomer to Angular 2, I am attempting to create a basic ng-form based on the official tutorial. Initially, everything works smoothly when using a simple array as shown:

 powers = ['Really Smart', 'Super Flexible',
        'Super Hot', 'Weather Changer'];

However, upon switching to my custom array fetched from an HTTP request:

  public departments = [];

  constructor(http: Http) {
    http.get('/api/departments')
      .map((res: Response) => res.json())
      .subscribe((departments: Array<Object>) => this.departments = departments);
  }

I encounter an error:

error_handler.js:51 Error: Uncaught (in promise): Error: Error in ./AddClientComponent - inline template:41:12 caused by: Cannot find a differ supporting object '[object Object]' of type 'departments'. NgFor only supports binding to Iterables such as Arrays.

Where could the mistake be and what am I overlooking? Appreciate your assistance in advance.

AddClientComponent

import 'rxjs/add/operator/map';

import {Component} from '@angular/core';
import {Http, Response} from '@angular/http';

import { DepartmentsComponent } from '../departments/departments.component';

@Component({
  selector: 'app-add-client',
  templateUrl: './add-client.component.html',
  styleUrls: ['./add-client.component.css']
})

export class AddClientComponent {

  public departments = [];
  public firstName = '';
  public lastName = '';
  public id = null;

  constructor(http: Http) {
    http.get('/api/departments')
      .map((res: Response) => res.json())
      .subscribe((departments: Array<Object>) => this.departments = departments);
  }

  model = new Employee(
    this.id,
    this.firstName,
    this.lastName,
    this.departments
  );

  submitted = false;

  onSubmit() { this.submitted = true; }

  active = true;

}

export class Employee {
  constructor(
    public id: number,
    public firstName: string,
    public lastName: string,
    public departments: any
  ) {  }
}

HTML Markup:

    <div class="container">
  <div  [hidden]="submitted">
    <h1>Employee Form</h1>
    <form *ngIf="active" (ngSubmit)="onSubmit()" #employeeForm="ngForm">

      <div class="form-group">
        <label for="firstName">First Name</label>
        <input type="text" class="form-control" id="firstName"
               required
               [(ngModel)]="model.firstName"
               name="firstName"
               #firstName="ngModel" >

        <div [hidden]="firstName.valid || firstName.pristine"
             class="alert alert-danger">
          First Name is required
        </div>
      </div>

      <div class="form-group">
        <label for="lastName">Last Name</label>
        <input type="text" class="form-control" id="lastName"
               required
               [(ngModel)]="model.lastName"
               name="lastName"
               #lastName="ngModel" >

        <div [hidden]="lastName.valid || lastName.pristine"
             class="alert alert-danger">
          Last Name is required
        </div>
      </div>

      <div class="form-group">
        <label for="departments">Department</label>
        <select class="form-control" id="departments"
                required
                [(ngModel)]="model.departments"
                name="departments"
                #departments="ngModel" >
          <option
            *ngFor="let department of departments"
            [value]="department">{{department.name}}
          </option>
        </select>

        <div [hidden]="departments.valid || departments.pristine"
             class="alert alert-danger">
          Department is required
        </div>
      </div>

      <button type="submit"
              class="btn btn-default"
              [disabled]="!employeeForm.form.valid">Submit
      </button>
      <!--<button type="button"-->
              <!--class="btn btn-default"-->
              <!--(click)="newHero()">New Hero-->
      <!--</button>-->
    </form>
  </div>

  <div [hidden]="!submitted">
    <h2>You submitted the following:</h2>
    <div class="row">
      <div class="col-xs-3">First Name</div>
      <div class="col-xs-9  pull-left">{{ model.firstName }}</div>
    </div>
    <div class="row">
      <div class="col-xs-3">Last Name</div>
      <div class="col-xs-9 pull-left">{{ model.lastName }}</div>
    </div>
    <div class="row">
      <div class="col-xs-3">Department</div>
      <div class="col-xs-9 pull-left">{{ model.departments }}</div>
    </div>
    <br>
    <button class="btn btn-default" (click)="submitted=false">Edit</button>
  </div>
</div>

Answer №1

Consider using a unique identifier for

#departments="ngModel"

Using the same name may cause conflicts with the departments property of the class utilized in the *ngFor directive

Answer №2

Experiment with modifying the data type

private officeDepartments: Array<any> = [];

constructor(httpService: Http) {
  httpService.get('/api/office-departments')
    .map((dataResponse: Response) => dataResponse.json())
    .subscribe((dept: Array<any>) => this.officeDepartments = dept);
 }

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

How can we update the form builder or form group in Angular 2 when making changes to the existing data in a table? I'm a bit confused on how to implement router

<tr *ngFor="let row of categories "> <td>{{row.categoryName}}</td> <td>{{row.visible}}</td> <td>{{row.instanceNumber}}</td> <td> <a class="btn btn-info btn-fill " [routerLink]="['/con ...

Sharing information between components in Angular 2 that are not directly related as parent-child relationships

Hey there, I'm just getting started with Angular 2 and ran into a bit of a roadblock. In my homepage component, I have a ul element where I display job descriptions fetched from a Firebase API call. The data is stored in an array called "jobs" and dis ...

Building Individual Elements in Angular 2

My task involves creating two distinct components in Angular 2, the Users component and the Clients component. These components are not nested and do not have any relationship. To call these components separately, I typically use main.ts as the main entry ...

Develop a Java RESTful server with an Angular 5 client that utilizes POST and PUT syntax for communication

Currently, I am in the process of learning the HTTP REST/CRUD protocol in an attempt to establish communication between a Java RESTful servlet and an Angular5 client. I have successfully implemented the GET and DELETE functionalities, however, I am encount ...

Exploring Angular Scope within a Typescript-based javascript function

My current setup involves Typescript with Angular combined with Breezejs. class CounterController { count: number = 0; static $inject = ['$scope']; constructor($scope) { $scope.vm = this; } setCount14(): void { ...

Exploring Angular's @Input feature for components buried deep within the hierarchy

As a newcomer to Angular, I am diving into the best approach for addressing a specific scenario. On my page, I have multiple tiles resembling mat-cards, each equipped with various functionalities such as displaying charts, tables, and associated actions. ...

Breaking down observables into smaller groups in RxJS

My goal is to execute a pool of observables in chunks with an interval added in between each chunk. I attempted the following code: let i = 0; from([].constructor(20)).pipe( concatMap(a => of(i).pipe(delay(1000))), // add a delay me ...

Issues with the rating plugin functionality in Ionic 3

After following the instructions in this tutorial: http://ionicframework.com/docs/native/app-rate/ Even though I implemented the second method, I encountered the following error: Uncaught (in promise): TypeError: Cannot read property 'split' ...

What is the best way to access the data being sent to a router link in Angular?

After navigating to the user page using the router sample below, how can I retrieve the details once it reaches the user page? I need to verify in my user.component.ts that the navigation is triggered by this [routerLink]="['user', user.id, &apo ...

Webpack encountering issues with loading dependencies within dependencies

When I try to run webpack, it seems that the compiler is having trouble loading my app.module from within main.ts. Without using webpack, my application can find all modules correctly, but with Webpack, it's failing. This is my webpack configuration: ...

The act of using the reset() function to clear form fields often leads to issues and

I have successfully implemented the use of ngForm in HTML and reset form fields using OnClickSubmit() in TypeScript. However, I am facing an issue where after resetting the form, there are 400 bad errors for API calls that populate the form fields. For exa ...

Encountered an issue finding element with Protractor - Error: script timed out after 20 seconds without receiving a response

I recently created a basic website using Angular 6 and I am facing some challenges while writing e2e tests for it. The first script is causing a lot of trouble for me as it throws the following error: C:\Users\user\Documents\workspace- ...

"In the combined declaration of 'DepartmentListComponent', all individual declarations must either be exported or kept local." - error message regarding routing components in TypeScript file

I followed a video tutorial to write this code, but it's not working as expected and is throwing some errors. Is it possible that the tutorial is outdated and using an older methodology? The code seems to be hard-coded without using any services. Her ...

Exploring the functionality of typeahead with server-side data integration

I am utilizing ng-select with Angular 7 and creating the following component: export class PostComponent { selectedCategoryID: number; allCategories$: Observable<CategoryModel[]>; constructor(private catService: CategoryService) { } ngOn ...

Obtain an Azure AD access token for an Angular application using the client_secret key in the client credential flow

Our client has requested the implementation of a trusted subsystem design, where their Azure AD (Client AD) is used to authorize frontend users. They require us to utilize our own Azure AD (Dev AD) for authorizing the frontend to access the backend. We h ...

Attaching dynamic data to a specific element within an array

I have successfully created a demo where elements can be dropped into a specific area and their top and left values are displayed. I have also added functionality to remove dropped items and move them between different blocks. However, I am encountering so ...

Injecting Dependencies with Angular 2 and the Ability to Include Optional Parameters

One issue I'm facing is that I have multiple components in my Angular 2 application that require the same dependency. This specific dependency needs a string for the constructor. How can I instruct angular2 to use a specific instance of this type for ...

Looking to adjust the header height of an angular mat-table with column groups? The table I'm currently working on has both main headers and sub headers

I recently utilized some code snippets from this StackBlitz example. However, I am facing an issue with the height property not functioning as expected. Is there a method to customize the height of both the main header and subheader? th.mat-header-cell, ...

The configuration object is invalid. Webpack has been initialized with a configuration object that does not conform to the API schema

I recently created a basic helloworld react app through an online course, but I encountered the following error: Invalid configuration object. Webpack has been initialized with a configuration object that does not adhere to the API schema. - configur ...

The execution of the code within the subscription of the Http observable is not taking place

In our Front-End application using Angular 16.x.x, we have set up an Observable for making http requests in the orders checkout component. Within the subscription's .next() method, we have included a toastr message and a logger to ensure that the succ ...