Angular2注入的自定义服务未定义

时间:2016-11-07 11:35:14

标签: angular angular2-services

我正在尝试将一个自定义服务( MessageService )注入另一个自定义服务( ItemService )。在 ItemService 中未提及错误 MessageService
但是服务(MessageService和ItemService)都可以正常使用组件。

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);
  }

}

这里在ItemService中未定义msgService。 任何人都可以帮我解决这个问题吗?

1 个答案:

答案 0 :(得分:7)

问题是this.而不是ItemService

.catch(this.handleError);

应该是

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

this.继续指向handleError()

中的当前类实例