Nat4j
Nat4j

Reputation: 513

Angular2 Injected custom service is undefined

I am trying to inject one custom service(MessageService) into another custom service(ItemService). It throwing an error MessageService is undefied in ItemService.
But both the Services (MessageService and ItemService) are working fine with components.

mani.ts

import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app.module';
const platform = platformBrowserDynamic();
platform.bootstrapModule(AppModule);

app.module.ts

import { NgModule }      from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import { AppComponent }   from './app.component';
import { routing, routedComponents } from './app.routing';
import { ItemService } from './services/item.service';
import { MessageService } from './services/message.service';
import './rxjs-extensions';


@NgModule({
  imports:      
  [ BrowserModule, 
    routing, 
    FormsModule, 
    ReactiveFormsModule,
    HttpModule,

  ],
  declarations: [ AppComponent, routedComponents],
  providers: [
    MessageService,ItemService 
  ],
  bootstrap:    [ AppComponent ]
})
export class AppModule { }

message.service.ts

import { Injectable } from '@angular/core';
import { Subject }    from 'rxjs/Subject';
import { Message } from '../models/message';

@Injectable()
export class MessageService {
    constructor() { }

    showError(msg: string) {
        console.log('MessageService Alert::'+msg);
    }

}

item.service.ts

import { Injectable } from '@angular/core';
import { Http, Response, Headers, RequestOptions } from '@angular/http';
import { Item } from '../models/item';
import { MessageService } from '../services/message.service'
import { Observable } from 'rxjs';

@Injectable()
export class ItemService {
private restUrl = 'http://localhost:3000/';  // URL to web api

  constructor(
    private http: Http,
    private msgService: MessageService) { }

  getAllItems(): Observable<Item[]> {
    return this.http
      .get(this.restUrl+'items')
      .map( (res: Response) => res.json() as Item[])
      .catch(this.handleError);
  }

  private handleError(error: any): Promise<any> {
    console.error('An error occurred', error);
    let errorMsg = error.message || error;
    this.msgService.showError("errorMsg"); // msgService is undefined here.
    return Promise.reject(errorMsg);
  }

}

here the msgService is undefined in ItemService. can anyone help me to resolve this ?

Upvotes: 4

Views: 1897

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657118

The problem is this. not ItemService

.catch(this.handleError);

should be

.catch(this.handleError.bind(this));

for this. to keep pointing to the current class instance inside handleError()

Upvotes: 7

Related Questions