core.js encountered an issue at line 6210: TypeError - The function this.service.addDepartment does not exist

Whenever I attempt to click the 'Add' button on a web application that I'm constructing, an error pops up.

core.js:6210 ERROR TypeError: this.service.addDepartment is not a function
at AddEditDepComponent.addDepartment (add-edit-dep.component.ts:25)
at AddEditDepComponent_button_5_Template_button_click_0_listener (add-edit-dep.component.html:10)
at executeListenerWithErrorHandling (core.js:15265)
at wrapListenerIn_markDirtyAndPreventDefault (core.js:15303)
at HTMLButtonElement.<anonymous> (platform-browser.js:582)
at ZoneDelegate.invokeTask (zone-evergreen.js:406)
at Object.onInvokeTask (core.js:28540)
at ZoneDelegate.invokeTask (zone-evergreen.js:405)
at Zone.runTask (zone-evergreen.js:178)
at ZoneTask.invokeTask [as invoke] (zone-evergreen.js:487)

I'm puzzled as to what the issue could be. The addDepartment function appears to be correct from my perspective, but the error persists.

add-create-department.component.ts

import { Component, OnInit, Input } from '@angular/core';
import { SharedService } from 'src/app/shared.service';

@Component({
  selector: 'app-add-create-department',
  templateUrl: './add-create-department.component.html',
  styleUrls: ['./add-create-department.component.css']
})
export class AddCreateDepartmentComponent implements OnInit {

  constructor(private service : SharedService) { }

  @Input() dep: any;
  DepartmentId!:string;
  DepartmentName!:string;

  ngOnInit(): void {
    this.DepartmentId = this.dep.DepartmentId;
    this.DepartmentName = this.dep.DepartmentName;
  }

  addDepartment() {
    var val = {DepartmentId:this.DepartmentId,
                DepartmentName:this.DepartmentName};
    this.service.addDepartment(val).subscribe((res: { toString: () => any; })=>{
      alert(res.toString());
    });
  }

  updateDepartment() {
    var val = {DepartmentId:this.DepartmentId,
                DepartmentName:this.DepartmentName};
    this.service.updateDepartment(val).subscribe((res: { toString: () => any; })=>{
      alert(res.toString());
    });

  }
}

I suspect it might have something to do with 'res' because I previously encountered an error stating "res is an implicit any type" and used QuickFix in VS Code to address it. However, the updateDepartment function is almost identical and seems to be functioning correctly, so I am unsure of the problem.

This includes all the files I've been working on today. Any assistance would be greatly appreciated.

show-list-departments.component.html

<!-- Button trigger modal -->
<button type="button" class="btn btn-primary float-right m-2" 
data-bs-toggle="modal" data-bs-target="#exampleModal"
(click)="addClick()"
data-backdrop="static" data-keyboard="false">
  Add Department
</button>

<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
  <div class="modal-dialog modal-dialog-centered modal-xl" role="document">
    <div class="modal-content">
      <div class="modal-header">
        <h5 class="modal-title" id="exampleModalLabel">{{ModalTitle}}</h5>
        <button type="button" class="btn-close" 
        data-bs-dismiss="modal" aria-label="Close"
        (click)="closeClick()" >
        </button>
      </div>
      <div class="modal-body">
        lt;app-add-create-department
          [dep]="dep" *ngIf="ActivateAddCreateDepartmentComp">
        </app-add-create-department>
      </div>
    </div>
  </div>
</div>

<table class = "table table-striped"> 
    <thead>
        <tr>
            <th>Department ID</th>
            <th>Department Name</th>
            <th>Options</th>
        </tr>
    </thead>
    <tbody>
        <tr *ngFor = "let dataItem of DepartmentList">
            <td>{{dataItem.DepartmentId}}</td>
            <td>{{dataItem.DepartmentName}}</td>
            <td>
                <button type="button" class = "btn btn-light mr-1"
                data-bs-toggle="modal" data-bs-target="#exampleModal"
                (click)="editClick(dataItem)"
                data-backdrop="static" data-keyboard="false">
                    Edit
                </button>
                <button type="button" class = "btn btn-light mr-1&...

add.create-department.component.html

<div class = "form-froup row">

    <label class = "col-sm-2 col-form-label"> Department Name </label>
    <div class = "col-sm-10">
        <input type = "text" class = "form-control" [(ngModel)] = "DepartmentName"
        placeholder = "Enter department name">
    </div>
</div>

<button (click) = "addDepartment()" *ngIf = "dep.DepartmentId == 0" class = "btn btn-primary">
    Add
</button>

<button (click) = "updateDepartment()" *ngIf = "dep.DepartmentId != 0" class = "btn btn-primary">
    Update
</button>

shared-services.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { Observable } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class SharedService {
  [x: string]: any;

  readonly APIUrl = "http://localhost:59281/api";
  readonly PhotoUrl = "http://localhost:59281/Photos";

  constructor(private http:HttpClient) { }

  getDepList():Observable<any[]> {

    return this.http.get<any>(this.APIUrl + '/Department');
  }

  getDepartment(val:any) {
    return this.http.post(this.APIUrl + '/Department', val);
  }

  updateDepartment(val:any) {
    return this.http.put(this.APIUrl + '/Department', val);
  }

  deleteDepartment(val:any) {
    return this.http.delete(this.APIUrl + '/Department/' + val);
  }

  getEmpList():Observable<any[]> {

    return this.http.get<any>(this.APIUrl + '/Employee');
  }

  getEmployee(val:any) {
    return this.http.post(this.APIUrl + '/Employee', val);
  }

  updateEmployee(val:any) {
    return this.http.put(this.APIUrl + '/Employee', val);
  }

  deleteEmployee(val:any) {
    return this.http.delete(this.APIUrl + '/Employee/' + val);
  }

  UploadPhoto(val:any) {
    return this.http.post(this.APIUrl + 'Employee/SaveFile', val);
  }

  getAllDepartmentNames():Observable<any[]> {
    return this.http.get<any[]>(this.APIUrl + '/Employee/GetAllDepartmentNames');
  }

}

Answer №1

The absence of the addDepartment(val:any) function in your SharedService class is causing the issue here. The error messages are leading you directly to the root cause.

You are attempting to execute this.service.addDepartment(val) within the addDepartment() method of the AddEditDepComponent

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

Ways to retrieve the most recent state in a second useEffect call?

Currently, I am encountering a situation where I have implemented two useEffect hooks in a single component due to the presence of two different sets of dependencies. My challenge lies in the fact that even though I update a state within the first useEffec ...

What is the best way to eliminate the "0"s from the center of items within an array?

I have developed a table sorter that handles columns containing both letters and numbers, such as "thing 027". To facilitate sorting, I prepended zeros to the numbers. However, I am now looking for a cleaner way to remove these zeros from the numbers using ...

Generate star icons dynamically within a div using C# and MSSQL data to determine the number of stars

Upon retrieving a rating (which can be more than 5) from the database, I aim to dynamically generate glyphicon stars based on the received value when the page loads. The code snippet below demonstrates how the value is retrieved: int rating_count = DBinte ...

Leveraging Handlebars Object within JavaScript

Is there a way to pass an entire object into javascript directly? I've tried using the {{{data}}} and {{data}} methods as suggested in other posts, but it doesn't seem to be working for me. Here's what I have in my handlebars file: <scri ...

How do I access the variable value from inside a function in jQuery?

Is it possible to extract the value from 'a = entry.username' outside of the function? I need to retrieve a value that is already being looped inside the function. $('#btnlogin').click(function(){ var usernamelogin = $(&apos ...

invoke a function through a form in Angular

I am encountering an issue with invoking a function from Angular. This particular function has a dual purpose - it uploads an image to S3 and saves the form data along with the URL of the image in the MongoDB database. Below is the HTML snippet where I cal ...

Looking to handle a .csv file containing both quotes and commas within the quotes in Node.js - how can I achieve this

My code solution successfully parses a CSV file, but it doesn't handle cases where data has commas within quoted fields. For example, "not, accounted","normal". let filePath = Path.resolve(__dirname, `./MyData.csv`); let data = fs.readFileSyn ...

Discover the process of loading one controller from another controller in Angular JS

Is it possible to load an entire controller1 from a different controller2, not just a function? ...

In JavaScript, split each element in an array into individual elements

Is there a way to split elements separated by commas into an array in JavaScript? ["el1,el2", "el3"] => ["el1", "el2", "el3"] I am looking for a solution to achieve this. Can you help me with that? ...

Preserve object properties while allowing for changes to be made without affecting

I am in need of transferring specific properties from one object to another while ensuring that the original object remains mutable. Here is the original object: var sourceObject = { "key1": "value1", "key2": "value2 ...

Exploring the World of Angularjs 2

Currently, I am diving into learning angularjs 2. I found a helpful git repository that I am following closely, which can be found here. The repository contains some interesting codes in the index.html file. <script src="node_modules/core-js/client/shi ...

Can the hexadecimal code for a particular color name be identified?

Similar Question: Javascript function to convert color names to hex codes Is there a way to determine the hexadecimal value of a named color that is currently being used by the browser? For example, I would like to achieve something similar ...

Unable to generate a fresh directory with mongoose and express

As the title suggests, I am working on an application that generates a link using mongoose _id and express's app.get when certain information is inputted. However, I am facing an issue where I have to reload the entire server in order to access the di ...

Issue with Laravel: unable to send data through ajax requests

I have developed a custom jQuery plugin specifically tailored for Laravel to facilitate sending data via Ajax to the server. However, I seem to be facing an issue where no data is being sent successfully. When I use dd($request->all()) to inspect what h ...

Refresh component when mobx store is modified

I am utilizing chart.js to display real-time price changes from the backend. The backend updates the frontend with new prices as they change, and stores the priceData (array) in a mobx store named priceChartStore. I need to continuously update the chart as ...

JQuery code causing issue with properly closing toggle menu

I am currently working on implementing a closing toggle menu for mobile devices and facing a minor issue. What I aim for is to allow users to close the toggle menu by tapping anywhere on the screen of their device while it is active. I have almost achieved ...

Obtaining an address using latitudes and longitudes with React Google Maps

I created a map using the react-google-map plugin where users can drag the marker to get the latitude and longitude of a location. However, I am only able to retrieve the lat and lng values and not the address. How can I obtain the address as well? Take a ...

Having difficulty asserting the dual-function button in both its disabled and enabled states

I have a button that is part of a dual-action setup. This button is disabled until a certain event occurs. Here is the DOM structure while the button is disabled: <div class="doc-buttons"> <a href="#" onclick="actualsize();" id="tip-size" cla ...

Is it recommended to update my peer dependencies when upgrading my RN version?

Recently, I took on the task of updating my old project from RN 0.61.x to 0.70.x and react 16 to react 18. During this process, I encountered a challenge with dependencies that were tied to older versions of React Native in their peer dependencies. This is ...

Customize Vue.js: Disable Attribute Quote Removal for Individual Pages

We have a requirement to turn off the minify.removeAttributeQuotes property for certain pages. This is the content of my vue.config.js: const packageJson = require('./package.json') module.exports = { assetsDir: packageJson.name + &apos ...