繁体   English   中英

使用Angular2在一个简单的类构造函数中注入服务

[英]Inject service in a simple class constructor with Angular2

我创建了一个这样的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,但这段代码甚至不起作用。 我收到此错误: 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));

我如何使用构造函数来实例化我的类并注入我的服务:
let nm = new Message(message);

谢谢

出于某种原因,我的答案被删除而没有解释,所以这里的答案是:

这正是我一直想知道的; 如果您真的需要在代码中调用构造函数并且仍需要在类中注入一些内容,该怎么办? 例如,Angular2教程的Hero类是贫血的,不包含任何真实的功能。 在我的应用程序中不是这种情况,我需要一个包含(很多)逻辑的域对象。

无论如何,这是我的方法:

@Injectable()
export class MessageFactory {
  constructor(private service: Service)

  build(data: any): Message {
    let message = new Message(data);
    message.service = this.service;
    return message;
  }
}

export class Message {
  service: Service;

  constructor(private data: any) {
    // Can't call service here but it's okay for me...
  }

  doSomethingWithService(): {
    this.service.doSomething(this.data);
  }
}

所以你可以在某处注入MessageFactory并创建Message的新实例:

export class MessageExampleComponent {
  constructor(private messageFactory: MessageFactory) {}

  makeMessageDoSomethingWithService(): {
    let message = this.messageFactory.build({just: 'an', example: 'here'})
    message.doSomethingWithService();
  }
}

我不确定调用它MessageFactory是否是一个正确的术语,但我想在一些主持人删除这篇文章而不发表评论之前对这种方法有反馈。

你可以在做这样的bootstrap时使用它

let nm = new Message(message);

bootstrap(AppComponent, [ 
  APP_ROUTER_PROVIDERS,
  [provide(Message,{useValue:nm})],
]).catch(err => console.error(err));

并为此

例外:错误:未捕获(承诺):没有Http的提供者! (ApiService - > Http)

在服务中创建构造函数并像这样导入HTTP

import { Http, Response } from '@angular/http';
export class LoginService {

  constructor(private http: Http) {

  }
}

以此目的

对不起,这不是我想要上课的方式。 对于我正在进行的聊天中的每条消息,我都会实例化一条消息。 我不想只有一个全局Message类,而是几个Message对象。

bootstrap(AppComponent, [ 
  APP_ROUTER_PROVIDERS,
  Message //you service here
]).catch(err => console.error(err));

我用@Inject解决了它

import { Inject } from "@angular/core;

我认为它应该像这样工作

@Inject(ApiService) api: ApiService;

import { Injectable , Inject } from "@angular/core;
    @Injectable()
    export class apiService {
        public constructor(@Inject(Http)  private http: Http) {}

    }
import { ReflectiveInjector, Component } from '@angular/core';

import { ApiService } from '../api.service';

@Component({
     providers: [ HomeService  ]
})

export class Message {
        timestamp: number;
        message: any;
        api: ApiService;

        constructor(message: any, @Inject(ApiService) api:ApiService) {                                      
                this.timestamp = message.timestamp;
                this.message = message.message;
        }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM