gpt4 book ai didi

Angular2 注入(inject)的自定义服务未定义

转载 作者:太空狗 更新时间:2023-10-29 17:46:49 26 4
gpt4 key购买 nike

我正在尝试将一个自定义服务 (MessageService) 注入(inject)到另一个自定义服务 (ItemService) 中。它抛出错误 MessageService is undefied in ItemService
但是这两个服务(MessageService 和 ItemService)都可以很好地处理组件。

ma​​ni.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 中是未定义的。谁能帮我解决这个问题?

最佳答案

问题是this.不是ItemService

.catch(this.handleError);

应该是

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

对于 this. 保持指向 handleError() 中的当前类实例

关于Angular2 注入(inject)的自定义服务未定义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40464222/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com