The 'admin' attribute is not found in the 'Object' data type

I have been facing this issue for quite some time now. The backend API response is indicating that a certain property does not exist, even though it clearly does. My Angular application suddenly started showing 18 errors today, and I am at a loss on how to resolve this "issue."

import { Component, OnInit, Output } from '@angular/core';
import { Router } from '@angular/router';
import { TokenService } from '../../authentication/services/token.service';
import { HttpErrorResponse } from '@angular/common/http';
import { AdminService } from '../../authentication/services/admin.service';
import { CrudService } from '../services/crud.service';
import { map } from 'rxjs/operators';

@Component({
  selector: 'app-users',
  templateUrl: './users.component.html',
  styleUrls: ['./users.component.css'],
})
export class UsersComponent implements OnInit {
  constructor(
    private _token: TokenService,
    private _router: Router,
    private _admin: AdminService,
    private _crud: CrudService
  ) {}

  adminId: string;
  adminName: string;
  adminEmail: string;
  users: any[];
  deletedId: string;
  successMessage: string;
  p: number = 1;
  loading: string;

  ngOnInit(): void {
    this.loading = 'true';
    this._token.verifyToken().subscribe(
      (res) => {
        this.adminId = res.admin._id;
        localStorage.setItem('adminid', this.adminId);
        this._admin.getAdminById(this.adminId).subscribe((res) => {
          this.adminName = res.admin.name;
          this.adminEmail = res.admin.email;
          this._crud.readAllUsers().subscribe((res) => {
            this.users = res.users;
            setTimeout(() => {
              this.loading = '';
            }, 950);
          });
        });
      },
      (err) => {
        if (err instanceof HttpErrorResponse) {
          if (err.status === 400) {
            this._router.navigate(['/login']);
          }
        }
      }
    );
  }

  deleteUserById(id: string) {
    this._crud.deleteUser(id).subscribe(() => {
      this._crud.readAllUsers().subscribe((res) => {
        this.users = res.users;
        this.successMessage = 'User successfully deleted';
      });
    });
  }

  removePopup() {
    this.successMessage = '';
  }
}

Answer №1

The reason for this issue is likely due to the HTTP calls being made without specifying a specific return type, causing TypeScript to infer the type as Object.

To resolve this, you can update the code in the ngOnInit method as follows:

  ngOnInit(): void {
    this.loading = 'true';
    this._token.verifyToken().subscribe(
      (res: any) => {
        this.adminId = res.admin._id;
        localStorage.setItem('adminid', this.adminId);
        this._admin.getAdminById(this.adminId).subscribe((res: any) => {
          this.adminName = res.admin.name;
          this.adminEmail = res.admin.email;
          this._crud.readAllUsers().subscribe((res) => {
            this.users = res.users;
            setTimeout(() => {
              this.loading = '';
            }, 950);
          });
        });
      },
      (err) => {
        if (err instanceof HttpErrorResponse) {
          if (err.status === 400) {
            this._router.navigate(['/login']);
          }
        }
      }
    );
  }

Additionally, make sure to include (res: any) as shown above.

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

Transforming a JavaScript object into a different shape

I need help converting a list of team objects containing team names, reporters, and statuses for each day into date-based objects with all teams and their respective statuses for each date. I attempted the following code snippet but did not achieve the de ...

What is the best way to implement a delay for ajax requests triggered by onkeyup events, and then restart the delay countdown each

Is there a way to add a delay for ajax requests triggered by onkeyup and reset the delay if onkeyup is triggered again? For instance, consider this code: When a user enters data into id="fname" triggering an onkeyup event, a loading span id="loading" wil ...

Send multiple input groups using Ajax POST requests

I need help setting up a form with 4 groups of checkboxes for refining search results. My goal is to send an array for each checkbox group that contains the IDs of the currently selected checkboxes. $.ajax({ url: "/stay_in_belfast/accommodation", t ...

How to toggle between checked and unchecked states using jQuery within AngularJS?

After reloading, the checkbox should maintain its checked or unchecked state. This functionality can be achieved using a directive controller. var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {}, $checkboxes = $("#c ...

Display a div beside it when hovering over a specific part of the image

If I have an image that is 200px wide and 900px tall How can I make a div display alongside it when hovering over a specific section of the image? ...

"Sorting functionality in Amcharts with dynamic movement of the div as the chart scroll bar is used

After exploring the question discussed here, I discovered that using li wasn't the most suitable option for me. Therefore, after further investigation and following the guidance provided in the example here, I successfully managed to create a customiz ...

Tips for updating an Observable array in Angular 4 using RxJS

Within the service class, I have defined a property like this: articles: Observable<Article[]>; This property is populated by calling the getArticles() function which uses the conventional http.get().map() approach. Now, my query is about manually ...

The error middleware in Express is not defined

I'm facing an issue where the Express API error messages are returning as undefined on the frontend. This is preventing me from displaying proper error messages to alert users. Interestingly, the error messages seem to appear fine in the developer to ...

Vue's intelligent element loading feature ensures that elements that are not displayed are delayed

My Vue gallery component includes a lightbox feature defined by the following code: <div id="lightbox" class="modal" v-if="photo !== null" v-show="showModal" @click.self="closeModal"> <div clas ...

Using Struts2 actions in combination with jQuery AJAX calls

Similar Question: How to utilize $.ajax() method in struts2 In simple terms: 1. Could someone explain how to trigger a struts action using jquery ajax? (without using the struts jquery plugin) 2. How do I retrieve results and display HTML output cor ...

Problem with the show/hide feature on jQuery. Automatically scrolls to the beginning of the page

On my website, I have successfully implemented two basic Show / Hide links that are working great. Here is the HTML code: <!DOCTYPE html> <html lang="en"> <head profile="http://gmpg.org/xfn/11"> <meta http-equiv="Content-Type" conte ...

The icons from Font Awesome are not displaying properly in Angular version 15

I have been searching for new information to help solve the error I am experiencing but haven't found any useful results. Here is my issue: I am working on a project in Angular 15.1.0 and want to incorporate some Font Awesome icons. To do this, I foll ...

TypeScript overload does not take into account the second choice

Here is the method signature I am working with: class CustomClass<T> { sanitize (value: unknown): ReturnType<T> sanitize (value: unknown[]): ReturnType<T>[] sanitize (value: unknown | unknown[]): ReturnType<T> | ReturnType< ...

Injecting JavaScript object values into dynamically generated modal

I have a JavaScript object that contains various training courses. Each category includes multiple training courses, and each course is associated with a specific category. Currently, I am able to display the title and description of each category in a mo ...

Determine selected option in Radio Button

FORM : <form id="approvalPenambahanUserInt" name="approvalPenambahanUserInt" action="" method="post"> <div class="form-group"> <div class="col-sm-12"> <label for= ...

What steps can I take to ensure that the information in my Cart remains consistent over time?

I recently built a NextJS application integrating the ShopifyBuy SDK. My implementation successfully fetches products from the store and displays them to users. Users can navigate to product pages and add items to their cart. However, I encountered an iss ...

Encountered an unhandled runtime error: TypeError - the function destroy is not recognized

While working with Next.js and attempting to create a component, I encountered an Unhandled Runtime Error stating "TypeError: destroy is not a function" when using useEffect. "use client" import { useEffect, useState} from "react"; exp ...

The .ajaxSubmit function in jquery.form.js seems to be malfunctioning when using the data option

I'm currently working with the jQuery plugin jquery.form.js and I'm looking to programmatically submit a form while including a file. Although I've set up the code and options to work with $.ajax, it's not functioning with .ajaxSubmit. ...

Creating a fixed sidebar that remains visible while scrolling in Next.js

Currently, I am faced with the challenge of implementing two components - a feed and a sidebar. The sidebar contains more content than it can display at once, so I want it to be able to overflow. My goal is to have the sidebar scroll along with the content ...

Using an element with the href property in conjunction with react-router: a comprehensive guide

My goal is to implement the navigation.push(url) functionality upon clicking an anchor tag element in order to prevent the app from refreshing when navigating to a new page, thus allowing me to maintain the application state. The decision to use this on a ...