Implementing Service Communication

I created an Angular Application using the Visual Studio Template.

The structure of the application is as follows:

  • /Clientapp
  • ./app/app.module.shared.ts
  • ./app/app.module.client.ts
  • ./app/app.module.server.ts
  • ./components/*
  • ./services/person-data.service.ts
  • ./services/auth-http.service.ts
  • ./boot-client.ts
  • ./boot-server.ts

In the person-data.service.ts file, I want to utilize the auth-http.service.ts.

person-data.service.ts

import { Person } from '../models/person'
import { Configuration } from '../constants/global.constants';
import { Injectable, Inject } from '@angular/core';
import { Http, Response, Headers } from '@angular/http';
import 'rxjs/add/operator/map';
import { Observable } from 'rxjs/Observable';
import { AuthHttpService } from '../services/auth-http.service';

@Injectable()
export class PersonService {
    constructor(private http: Http, @Inject(AuthHttpService)private authHttp: AuthHttpService) {

        this.actionUrl = Configuration.API_SERVER + 'api/person/';

        this.headers = new Headers();
        this.headers.append('Content-Type', 'application/json');
        this.headers.append('Accept', 'application/json');
    }

    public GetAll = (): Observable<Person[]> => {
        return this.authHttp.get(this.actionUrl).map((response: Response) => <Person[]>response.json());
    }
}

auth-http.service.ts

import { Injectable, Inject } from '@angular/core';
import { Http, Response, RequestOptions } from '@angular/http';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import { AuthService } from './auth.service';

@Injectable()
export class AuthHttpService {
    constructor(private http: Http, @Inject(AuthService) private authService: AuthService) {

    }
    get(url: string, options?: RequestOptions): Observable<Response> {
        console.log("AuthHttpService Get:" + url);
        if (options) {
            options = this.authService._setRequestOptions(options);
        } else {
            options = this.authService._setRequestOptions();
        }
        return this.http.get(url, options);
    }
}

app.module.shared.ts

import { NgModule } from '@angular/core';
import { RouterModule } from '@angular/router';
import { PersonService } from './services/person-data.service'
import { Configuration } from './constants/global.constants'
import { AuthService } from './services/auth.service'
import { AuthHttpService } from './services/auth-http.service'
import { AppComponent } from './components/app/app.component'

export const sharedConfig: NgModule = {
    bootstrap: [AppComponent],
    declarations: [
        AppComponent
    ],
    providers: [
        AuthHttpService,
        Configuration,
        PersonService,
        AuthService
    ],
    imports: [
        RouterModule.forRoot([
            { path: '', redirectTo: 'home', pathMatch: 'full' },
            { path: '**', redirectTo: 'home' }
        ])
    ]
};

app.module.client.ts

import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { sharedConfig } from './app.module.shared';


@NgModule({
    bootstrap: sharedConfig.bootstrap,
    declarations: sharedConfig.declarations,
    imports: [
        BrowserModule,
        FormsModule,
        HttpModule,
        BrowserAnimationsModule,
        ...sharedConfig.imports
    ],
    providers: [
        { provide: 'ORIGIN_URL', useValue: location.origin }
    ]
})
export class AppModule {
}

Upon running the application, I encountered the following error message:

An unhandled exception occurred while processing the request. Exception: Call to Node module failed with error: Error: No provider for AuthHttpService!

What could be causing this issue?

Answer №1

Consider eliminating the inject decorators from the constructor since they are unnecessary.

Next, as indicated by the error message, import them within the providers section of your module, such as:

providers: [
             AuthHttpService,
             // Additional services can go here,
             { provide: 'ORIGIN_URL', useValue: location.origin }
            ]

Answer №2

It seems like you may have overlooked

adding the sharedConfig.providers import to the app.module.client.ts

app.module.client.ts

...
providers: [
        ...sharedConfig.providers,
        { provide: 'ORIGIN_URL', useValue: location.origin }
    ]
...

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

Unable to designate data types for a React Higher Order Component

In order to enhance a component with flattened props, I am working on creating a Higher Order Component (HOC). The goal is to take a component and return a new one that accepts flattened props using the flat package, then apply these unflattened props to t ...

Linking children to their parents in a mat tree structure

I'm looking to create a mat tree based on the provided diagram. So far, I've managed to design the icons and boxes, but I'm struggling with drawing the connecting lines. Can anyone assist me with this part? I'm using a mat nested tree ...

An issue has occurred: TypeError - It is not possible to access the property 'loadChildren' as it is undefined

After incorporating modules, routing, and AuthGuard for redirection to login pages, I encountered an issue. I am able to navigate between the pages, the links are functioning properly, and the AuthGuard is redirecting as expected. However, a specific error ...

Encountering a SubprocessError while attempting an Ionic v4 production build

Encountering issues with Ionic v4 production builds on Ubuntu v.18. Upon running ionic build --prod, an error is thrown: Error at new SubprocessError (/root/.nvm/versions/node/v12.2.0/lib/node_modules/@ionic/cli/node_modules/@ionic/utils-subprocess/dist/i ...

Issue encountered when attempting to develop a countdown timer using Typescript

I am currently working on a countdown timer using Typescript that includes setting an alarm. I have managed to receive input from the time attribute, converted it using .getTime(), subtracted the current .getTime(), and displayed the result in the consol ...

Automate the selection of an item in a Primeng Listbox using Angular 2 and PrimeNg

After displaying a list using a PrimeNg Listbox (p-listbox), I needed to monitor the changes in selection by implementing the ngDoCheck lifecycle hook. Specifically, I wanted to detect when the user selected a specific group ("Group0") and then revert the ...

Tips for choosing and unchoosing rows in angular 6

I am looking to extract the values from selected rows and store them in an array. However, I also need to remove a row from the result array when it is deselected. The issue with my current code is that every time I click on a row, the fileName values are ...

Concerning the issue of components not loading correctly when using Angular with Lazy Loading Routing

Encountering an unusual issue while utilizing lazyload routing in our application! Within AppModule, there is TopModule followed by DashboardModule, all being loaded lazily. When localhost:4200/dashboard is accessed, the loading sequence is AppModule, To ...

Is there a way to retrieve the initial item of a JSON array from an HTML document using Angular 2?

Within the src/assets/ directory, I have a json file called product.json with the following structure: [ { "images": "http://openclipart.org/image/300px/svg_to_png/26215/Anonymous_Leaf_Rake.png", "textBox": "empty", "comments": "empty" }, { "i ...

Warning message regarding unhandled promise rejection in NestJS websockets

I've encountered a puzzling issue while attempting to integrate an 'events' module into my application to utilize websockets. Upon adding the module, an unexpected error surfaced: (node:59905) UnhandledPromiseRejectionWarning: Unhandled pro ...

Encountering an error with TypeScript in combination with Angular 2 and Grunt. The error message is TS

Currently in my angular2 Project, I am utilizing grunt for automating the compilation of my typescript files. Everything seems to be working fine as my files are compiling, but I keep encountering errors: app/webapp/ng2/audit_logs/auditLogs.ts(2,3): erro ...

Leveraging a component as a property of an object in Vue version 3

I'm trying to figure out if there's a way to use a Component as a property in Vue 3. Consider the TypeScript interface example below: import type { Component } from 'vue' interface Route { url: string icon: Component name: ...

Optimal Method for Inserting Lengthy Data using Sequelize

I have a table containing 20 elements. Is there a more concise way to input data into Sequelize without listing each element individually like this: Sequelize.create({ elem1: req.body.eleme1, elem2: req.body.eleme2, elem3: req.body.eleme3, elem4: ...

Angular: Exploring the Dynamic Loading of a Component from a String Declaration

Is there a way to compile a component defined by a string and have it render in a template while still being able to bind the click event handler? I attempted to use DomSanitizer: this.sanitizer.bypassSecurityTrustHtml(parsedLinksString); However, this a ...

Error encountered when referencing prop on textarea: 'There is no suitable overload for this call'

I've been referring to the documentation in order to set a reference using the useRef hook, with the goal of being able to programmatically clear an input field. However, when I add ref as a prop to a textarea, it triggers a lint error saying that no ...

If an interface property is set as (), what significance does it hold?

While exploring the Vue.js source code located at packages/reactivity/src/effects.ts, I came across this snippet: export interface ReactiveEffectRunner<T = any> { (): T effect: ReactiveEffect } I'm curious, what does () signify in the code ...

When dynamically selecting an item from a dropdown menu, the object property does not display as expected when using the patchValue

When attempting to set the value for a sort object with specific type and format, I encountered an issue where it was not being rendered. Below is my code snippet using patch to set the value: let arr = <FormArray>this.myForm.controls.users; arr.c ...

Explore the Attribute and generate a Text-Node using the Renderer

Given the advice against directly accessing the DOM in Angular for various platforms, I am trying to figure out how to achieve the following using Renderer: a) Store the offsetLeft value of $event.target in a variable called left. b) Create a text node wi ...

Looking to execute a service method within an authguard service?

I am a beginner with Angular and I am looking to invoke a service method within the authguard service. The specific service function that I need is as follows. Please note that I do not want to make any changes to this service function. loadOrganizations() ...

The Zoom-sdk functions properly on a local machine, but encounters issues when it is

Using zoom's API, jwt, and the websdk, I am able to create a meeting on button click, join as a host, and start the meeting for others to join. This process works flawlessly when running locally, but once deployed to Cloudflare, I encounter the follow ...