Issues with Injectable Service within Another Service in Angular 2

Having a problem with injecting a service into another service. I have a ContactService that retrieves data from the server using the handleError method, and an AlertService that handles errors thrown from the handleError method. Both services are declared in my Core Module. However, when I call alertService.submitNewMessage, it shows that this.alertService is undefined. Any assistance would be appreciated.

@Injectable()
export class AlertService {
  private $currentMessages: BehaviorSubject<string> = new BehaviorSubject('');
  public currentMessages: Observable<string> = this.$currentMessages.asObservable();
  constructor() { }

  submitNewMessage(msg: string): void {
    this.$currentMessages.next(msg);
  }

}

Contact Service:

@Injectable()    
export class ContactService {
      private contactsUrl = 'http://localhost/customers';
      constructor(
                  private http: Http,
                  private router: Router,
                  private alertService: AlertService
                  ) { }

      getContactsFromService(): Observable<SubmitCustomerHttp[]>  {
        return this.http.get(this.contactsUrl)
                        .map(this.extractData)
                        .catch(this.handleError);
      }

      private extractData(res: Response) {
        return HttpHelper.extractData(res);
      }

      handleError(error: Response | any) {
        let errMsg: string;
        console.log('Receive error: ', error);
        if (error instanceof Response) {
          const body = error.json() || '';
          const err = body.error || JSON.stringify(body);
          errMsg = `${error.status} - ${error.statusText || ''} ${err}`;
          if (error.status === 500 || 400 || 404) {
            window.alert(errMsg);
            this.alertService.submitNewMessage(errMsg);
            return errMsg;
          }
        } else {
          errMsg = error.message ? error.message : error.toString();
          console.log('Error Message: ', errMsg);
          return null;
        }
      }
    }

Core Module:

@NgModule({
  imports: [
    CommonModule,
    HttpModule,
    JsonpModule

  ],
  declarations: [],
  providers: [
    AlertService,
    ContactService,

  ]
})


export class CoreModule {
  static forRoot(): ModuleWithProviders {
    return {
      ngModule: CoreModule,
      providers: [
        AlertService,
        ContactService,

      ]
    };
  }
}

Answer №1

The issue I believe is connected to

return this.http.get(this.contactsUrl)
                .map(this.extractData)
                .catch(this.handleError);

In this code snippet, the class methods are registered as callbacks. The problem arises because this does not bind correctly.

To resolve this issue, you can modify the code by wrapping these in arrow functions. This way, this will still reference the service and not the callback function when the respective code is executed:

return this.http.get(data => this.contactsUrl(data))
                .map(data => this.extractData(data))
                .catch(data => this.handleError(data));

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

The challenges of type verification in Redux reducer

I'm currently facing two specific challenges with Typescript and the Redux reducer. Reducer: const defaultState = { selectedLocation: { id: 0, name: 'No Location' }, allLocations: [{ id: 0, name: 'No Location' }], sele ...

Error encountered while retrieving data from Firebase and storing it in an array within an IONIC application

I am currently working on a function that retrieves data from Firebase's real-time database and stores it in an array for mapping in React. However, I am encountering a TypeScript error that I'm having trouble resolving. The error message reads ...

Accessing properties using bracket notation in Typescript is a powerful feature that

I wish to retrieve a typed object using bracket notation like this: interface IFoo { bar: string[]; } var obj: IFoo = { bar: ["a", "b"] } var name = "bar"; obj[name]. // type information lost after dot As per the specification 4.10, it seems to be t ...

Utilizing Angular's primeng library with CommonJS or AMD dependencies may lead to optimization setbacks

I recently updated my Angular app and started using PrimeNG components. However, after the update to Angular 10, I've been encountering a Warning message: CommonJS or AMD dependencies can cause optimization bailouts. This warning appears for variou ...

What is the process for specifying an input for a component?

When defining an input for a component like this: @Input() person: Person, some encountered the error message saying, "property 'person' has no initializer and is not definitely assigned in the constructor" even though the Person model has been i ...

Incorporate the Angular router within markdown hyperlinks

When utilizing ngx-markdown to display my FAQ, I include links to both external resources (beginning with http) and internal content (starting with /). I am interested in passing the Angular router to my markedOptionsFactory so that I can easily navigate ...

Is it considered a poor practice to utilize a store in an effect?

Within my InitAction, there are various parameters such as a profile id and other data. This action can be executed multiple times with different parameters. In addition, I have a LoadProfileAction with an effect that listens to the InitAction and trigger ...

Leveraging CSS attribute selectors within JSX using TypeScript

With pure HTML/CSS, I can achieve the following: <div color="red"> red </div> <div color="yellow"> yellow </div> div[color="red"] { color: red; } div[color="yellow"] { color: yellow; ...

Using typescript with Ramda's filter and prop functions can lead to unexpected errors

I'm new to TypeScript and currently facing the challenge of converting JavaScript functions that use Ramda library into TypeScript functions. The lack of clear TypeScript usage in the Ramda documentation is making this task quite difficult for me. Sp ...

Angular 2: A guide to dynamically adding and updating meta tags through a component, similar to the title service functionality

As someone who is just beginning to explore Angular 2, I find myself in need of setting up meta tags such as og: description and others directly from a component. I am unsure of how to dynamically update these meta tags or add new ones to the index.html fr ...

Display an error popup if a server issue occurs

I'm considering implementing an Error modal to be displayed in case of a server error upon submitting a panel. I'm contemplating whether the appropriate approach would be within the catch statement? The basic code snippet I currently have is: u ...

Only one choice for discriminated unions in react props

Looking to create a typescript type for react component props, specifically a basic button that can accept either an icon prop or a text prop, but not both. My initial attempt with a discriminated union didn't quite produce the desired outcome: inter ...

The Type {children: Element; } is distinct and does not share any properties with type IntrinsicAttributes

I am encountering an issue in my React application where I am unable to nest components within other components. The error is occurring in both the Header component and the Search component. Specifically, I am receiving the following error in the Header co ...

What is the best way to shorten text in Angular 2?

Can the length of a string be limited to a specific number of characters in AngularJS code? For example, if I need to restrict the title length to 20 characters {{ data.title }}. Is there a built-in pipe or filter available to set this character limit? ...

Preact: occasional occurrence of a blank page after refreshing

Starting out with Preact & TypeScript, I decided to kickstart my project using the parcel-preact-typescript-boilerplate. Initially, everything seemed to be working smoothly. However, I noticed that occasionally, especially on reload or initial page lo ...

Limit pasted content in an Angular contenteditable div

Is there a way to limit the input in a contenteditable div? I am developing my own WYSIWYG editor and want to prevent users from pasting content from external websites and copying styles. I want to achieve the same effect as if the content was pasted into ...

Error message: Angular material StaticInjectorError - MatDialog provider not found

After trying to launch my Angular 5 page in the browser, I encountered an error message in the console. ERROR Error: StaticInjectorError(AppModule)[AppComponent -> MatDialog]: StaticInjectorError(Platform: core)[AppComponent -> MatDialog]: ...

Is there a way to reset the selected value of a specific option in Mat-Select?

Using mat-select, I need to reset the selection for a specific value of mat-select's mat-option. For instance, take a look at this example on StackBlitz In the example, the mat-select has three options; when selecting Canada, it should revert back t ...

Make sure that every component in create-react-app includes an import for react so that it can be properly

Currently, I am working on a TypeScript project based on create-react-app which serves as the foundation for a React component that I plan to release as a standalone package. However, when using this package externally, I need to ensure that import React ...

"Encountering an issue with Angular2 where @Input is showing as undefined when attempting to bind

Perhaps it's normal to encounter this issue while testing this.myColor. It appears to be undefined, but why is that? Here's the mistake in my code: <h1 myDR [myColor]="red" > Test </h1> import {Component, Directive, Input, ...