【发布时间】:2016-07-27 18:12:22
【问题描述】:
我创建了一个这样的 Message 类
import { ReflectiveInjector } from '@angular/core';
import { ApiService } from '../api.service';
export class Message {
timestamp: number;
message: any;
api: ApiService;
constructor(message: any) {
let injector = ReflectiveInjector.resolveAndCreate([ApiService]);
this.api = injector.get(ApiService);
this.timestamp = message.timestamp;
this.message = message.message;
}
}
我没有直接在构造函数参数中注入 ApiService,因为我试图避免这种情况:
let nm = new Message(message, this.api)
我不希望服务出现在参数中。
所以我正在使用 ReflectiveInjector,但这段代码甚至不起作用。我收到此错误:例外:错误:未捕获(承诺):没有 Http 提供者! (ApiService -> Http) 即使我以这种方式包含 HTTP_PROVIDERS
import { bootstrap } from '@angular/platform-browser-dynamic';
import { enableProdMode } from '@angular/core';
import { HTTP_PROVIDERS } from '@angular/http';
import { AppComponent, environment } from './app/';
import { appRouterProviders } from './app/app.routes';
if (environment.production) {
enableProdMode();
}
bootstrap(AppComponent, [
appRouterProviders,
HTTP_PROVIDERS,
])
.catch(err => console.log(err));
如何使用构造函数来实例化我的类并像这样注入我的服务:let nm = new Message(message);
谢谢
【问题讨论】:
标签: class typescript angular