Gre*_*reg 5 class typescript angular
我创建了一个这样的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;
}
}
Run Code Online (Sandbox Code Playgroud)
我不是直接在构造函数参数中注入ApiService,因为我试图避免这种情况:
let nm = new Message(message, this.api)
我不希望服务在参数中.
所以我使用的是ReflectiveInjector,但这段代码甚至不起作用.我收到此错误:EXCEPTION:错误:未捕获(在承诺中):没有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));
Run Code Online (Sandbox Code Playgroud)
我如何使用构造函数来实例化我的类并注入我的服务:
let nm = new Message(message);
谢谢
你可以在像这样进行引导时使用它
let nm = new Message(message);
bootstrap(AppComponent, [
APP_ROUTER_PROVIDERS,
[provide(Message,{useValue:nm})],
]).catch(err => console.error(err));
Run Code Online (Sandbox Code Playgroud)
并为此
例外:错误:未捕获(承诺):没有 Http 提供者!(ApiService -> HTTP)
在服务中创建构造函数并像这样导入HTTP
import { Http, Response } from '@angular/http';
export class LoginService {
constructor(private http: Http) {
}
}
Run Code Online (Sandbox Code Playgroud)
以此目的
哦,抱歉,这不是我想要使用我的课程的方式。对于我在聊天中发出的每条消息,我都会实例化一条消息。我不想要一个全局 Message 类,而是多个 Message 对象。
bootstrap(AppComponent, [
APP_ROUTER_PROVIDERS,
Message //you service here
]).catch(err => console.error(err));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3590 次 |
| 最近记录: |