2016-11-07 57 views
3

我試圖注入一個定製服務(MessageService)到另一個定製服務(ItemService)。它拋出一個錯誤MessageServiceItemService undemonstrable。
但這兩個服務(MessageService和ItemService)都可以正常使用組件。Angular2注入定製服務是未定義

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

} 

這裏msgService在ItemService不確定。 任何人都可以幫我解決這個問題嗎?

回答

7

問題是this.ItemService

.catch(this.handleError); 

應該

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

this.保持指向當前類的實例裏面handleError()

+0

哦,我看..但如果我這樣做所以得到typewriter錯誤爲'Observable <{}>不能分配給類型'Observable '。我仍然無法取得進展。 –

+0

我自己並不使用TypeScript,也不知道TS中的泛型(在Plunker中它們沒有被選中)。也許'.map ((res:Response)=> res.json()as Item [])''。 –

+1

改變'.catch(res => { this.messageService.showAlert(res); return Observable.throw(res); });'工作:-) –