Despite passing the same dependency to other services, the dependencies in the constructor of an Angular2 Service are still undefined

To successfully integrate the "org-agents-service" into the "org-agents-component," I need to resolve some dependencies related to the required api-service. Other components and services in the hierarchy are also utilizing this api-service, which acts as a wrapper for the http module.

While most components and services have no issues with dependency injection, the org-agents service is presenting an error message that reads:

browser_adapter.js:84EXCEPTION: Can't resolve all parameters for OrgAgentsService: (?).

/app-component
    /dashboard-component
       /agent-search-component
           *search-service
               *api-service
       /task-search-component
           *search-service
               *api-service
       /search-view-component
           *search-service
               *api-service
       /org-agents-component
           *org-agents-service
               *api-service

The service code below showcases how OrgAgentsService depends on the ApiService, successfully injected into other services. The type of error we face seems tied to resolving these dependencies properly.

import {Injectable} from '@angular/core'
import {ApiService} from '../common/services/api.service'
import {Agent} from '../models/agent.model'

@Injectable();
export class OrgAgentsService {
    constructor(private apiService: ApiService) {

    }
    public orgId: number;
    public agents: Agent[];

    public retrieveAgentsList(orgId) {
        let url: string = `https://blahblahblah.blah.blah/endpoint/${orgId}/agents`;

        return this.apiService.get(url).map((data, err) => {
            if(!err) {
                for(let agentResult of data.body) {
                    let agentModel = this.extractAgentSearchResult(agentResult);
                    this.agents.push(agentModel)
                }
                return this.getAgents();
            }
            console.log(`[ERROR: OrgAgentService] could not retrieve agents for org ${this.orgId}`);
            return null
        })
    }

    public getAgents(): Agent[] {
        return this.agents
    }

    private extractAgentSearchResult(item: any): Agent {
        console.log(" agent data: " + JSON.stringify(item));
        let id = item["id"];
        let name = item["name"];
        let email = item["email"];
        let foreign_id = item["foreign_id"];
        let org_id = item["org_id"];
        let roles = "";
        for (var i = 0, n = item["roles"].length; i < n; i++) {
            roles = roles + item["roles"][i] + " ";
        }
        return new Agent(id, name, email, foreign_id, org_id, roles)
    }
}

Below, you can see the component responsible for requiring the OrgAgentsService. It comprises various methods for handling agent-related functionalities within the organization's context.

import {Component, OnInit, OnChanges} from '@angular/core'
import {OrgAgentsService} from "../../services/org-agents.service";
import {Agent} from '../../models/agent.model'
import {AgentDetailComponent} from '../agent-detail/agent-detail.component'
import {ApiService} from "../../common/services/api.service";

@Component({
    selector: 'org-agents-list',
    providers: [OrgAgentsService, ApiService],
    directives: [AgentDetailComponent],
    template: require('./org-agents.template.html')
})
export class OrgAgentsComponent implements OnInit, OnChanges {
    constructor(private orgAgentsSvc: OrgAgentsService) {

    }
    private agents: Agent[];
    public agentId: number;
    private orgId: number;

    ngOnInit() {
        this.getAgents()
    }

    ngOnChanges() {
        this.getAgents();
    }

    getAgents() {
        this.orgAgentsSvc.retrieveAgentsList(this.orgId).subscribe(agents=>{
            this.agents = agents;
        });
    }
    onSelect(agent: Agent){
        this.agentId = agent.id;
        let elem = <HTMLElement>document.querySelector('#agentDetailsModalOrgList ');
        elem.style.display="block";
    }

    private onAgentDetailsClose($event){
        let elem = <HTMLElement>document.querySelector('#agentDetailsModalOrgList ');
        elem.style.display="none";
    }
}

Answer №1

It was bothering me for quite some time until I finally realized it was a syntax error. In your OrgAgentsService, I noticed that you used Injectable() instead of @Injectable(). Is this a copy-paste mistake or does the original code actually have it like that? Additionally, there is a semicolon at the end which shouldn't be there.

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

Angular - The differ is unable to find support for the object 'Item One' which is of type 'string'. NgFor is only able to bind to Iterables like Arrays and not individual objects

Many questions on StackOverflow share similarities with this one, but I have not been able to find a solution that fits my issue. My code functions correctly when attempting to populate items in a "Select" control. It successfully retrieves data if the it ...

Implementing validation logic on button click using TypeScript

I'm struggling to get my validation to work for empty fields using the method below. Can anyone provide some guidance or suggestions? Thanks. Here is my template: <form [formGroup]="form" (ngSubmit)="onSubmit(form.value)" class="nobottommargin ad ...

What is the best way to effectively nest components with the Nebular UI Kit?

I'm currently facing an issue with nesting Nebular UI Kit components within my Angular app. Specifically, I am trying to nest a header component inside the home page component. The problem arises when the attributes take up the entire page by default, ...

The service being injected is not defined

Two services are involved in this scenario, with the first service being injected into the second service like so: rule.service.ts @Injectable() export class RuleService { constructor( private _resourceService: ResourceService ){} s ...

Can't figure out why the BackgroundImage URL from process.env isn't appearing on my website

Having trouble setting a background image on my website that connects with my backend to determine which image should appear. However, in some cases, the image isn't showing up. When attempting to add a background image using the code below within a ...

Employing square bracket notation based on the input data

I'm currently in the process of enhancing some code within my library, but I've encountered a perplexing issue with bracket notation not functioning as expected when attempting to call an imported class. The parameter type expects a camelCased s ...

Implementing a string replacement within an array of objects using TypeScript

I have a collection of array objects displayed below [ { "subjectID": 1 "Chosen" : "{subjectsChosen:Python,java,Angular}" "password": "{studentpw:123456abcd}" }, { "subjectID": 2 ...

Error in Mocha test: Import statement can only be used inside a module

I'm unsure if this issue is related to a TypeScript setting that needs adjustment or something else entirely. I have already reviewed the following resources, but they did not provide a solution for me: Mocha + TypeScript: Cannot use import statement ...

Implementing ControlValueAccessor in Angular 2 - A step-by-step guide

I'm encountering the error message "No value accessor for form control with unspecified name attribute" Some suggest adding ngDefaultControl, but it doesn't make any difference in my component When I try to use ControlValueAccessor instead, I s ...

Issues arising with code splitting using React HashRouter in a project utilizing Typescript, React 17, and Webpack 5

Encountered build issues while setting up a new project with additional dependencies. package.json: { "name": "my-files", "version": "1.0.0", "description": "App", "main": " ...

Encountering a type-safety problem while attempting to add data to a table with Drizzle

My database schema is structured like so: export const Organization = pgTable( "Organization", { id: text("id").primaryKey().notNull(), name: text("name").notNull(), createdAt: timestamp("c ...

Angular issue: Element 'mdb-select' is unrecognized

While working with Angular's MDB pro version, I encountered a peculiar error message: mdb-select is now a known element I suspect that I may have missed an import somewhere, but the specific one eludes me This snippet shows my component.html file: ...

Angular15 experiencing issues with Grid from Bootstrap

I am attempting to create a basic webpage using the bootstrap grid system, but I am encountering some issues with its functionality. Here is the code from my app-component.html file: <body> <div class="container"> <div class=& ...

Tips for passing the indexes of an array within nested ngFor loops in Angular

I have a 2D grid in my component that is created using nested ngFor loops, and I want to make certain grid elements clickable under specific conditions so they can call a function. Is there a way for me to pass the index of the clicked array element to the ...

The development mode of NextJS is experiencing issues, however, the build and start commands are functioning normally

Just finished creating a brand new Next app (version: 12.0.7) using Typescript and Storybook. Everything seems to be working fine - I can successfully build and start the server. However, when I try to run dev mode and make a request, I encounter the follo ...

Restricting access to tabPanel in tabView when a tab is clicked using Angular

In my tabview, I have multiple tabpanels and I am able to programmatically control it using the [activeIndex] property. However, I am facing an issue where I want to display an alert and deny access to a specific tab if a certain variable is set to false. ...

Why is the selected option not visible in the Angular 8 drop-down?

This is a commonly asked question, but my situation seems to be unique. None of the existing answers have provided a solution for my specific issue. Here is the code that I am working with: <form (ngSubmit)="getExceptions(f)" #f="ngForm"> ...

Exploring the potential of Vue with Router to create a dynamic multi-page

Struggling to come up with a suitable title for this Vue project dilemma. Here's what I'm facing: Recently started using Router in my Vue project and feeling quite lost. The setup in App.vue simply includes <RouterView>, which seems stra ...

Difficulty in dynamically changing Angular 6 directive attributes

I am currently working with component A, which features a custom directive on the web page: Here is how it looks: <warning [details]='details'></warning> The code for Component A is as follows: export class AComponent implemen ...

CSS not working when attempting to override Angular (13) Material file

In my Angular (13) application with Material, I have developed a CSS file specifically for overriding certain Material styles. This CSS file is imported into the styles.scss file as the last line. However, despite importing the external file, the CSS def ...