简体   繁体   English

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

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

I created a Message class like this 我创建了一个这样的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;
        }
}

I'm not injecting ApiService directly in the constructor parameters because I'm trying to avoid this: let nm = new Message(message, this.api) 我不是直接在构造函数参数中注入ApiService ,因为我试图避免这种情况: let nm = new Message(message, this.api)
I don't want the service to be in the parameters. 我不希望服务在参数中。

So I'm using the ReflectiveInjector but this code doesn't even work. 所以我使用的是ReflectiveInjector,但这段代码甚至不起作用。 I get this error : EXCEPTION: Error: Uncaught (in promise): No provider for Http! 我收到此错误: EXCEPTION:错误:未捕获(在承诺中):没有Http的提供者! (ApiService -> Http) even if I include HTTP_PROVIDERS this way (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));

How can I use the constructor to instantiate my class and inject my services like this : 我如何使用构造函数来实例化我的类并注入我的服务:
let nm = new Message(message);

Thanks 谢谢

For some reason my answer was deleted without explanation, so here's the answer again: 出于某种原因,我的答案被删除而没有解释,所以这里的答案是:

This is exactly what I have been wondering; 这正是我一直想知道的; What if you really need to call a constructor in your code & still need to inject some things in your class? 如果您真的需要在代码中调用构造函数并且仍需要在类中注入一些内容,该怎么办? For example Angular2 tutorial's Hero class is anemic and does not contain any real-world functionality. 例如,Angular2教程的Hero类是贫血的,不包含任何真实的功能。 That's not the case in my application, I need to have a domain objects that contain (a lot of) logic. 在我的应用程序中不是这种情况,我需要一个包含(很多)逻辑的域对象。

Anyway, this is my approach: 无论如何,这是我的方法:

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

So somewhere you can inject MessageFactory and create new instances of Messages: 所以你可以在某处注入MessageFactory并创建Message的新实例:

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

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

I'm not sure if calling it MessageFactory is even a correct term, but I would like to have a feedback on this approach before some moderator just deletes this post without comment. 我不确定调用它MessageFactory是否是一个正确的术语,但我想在一些主持人删除这篇文章而不发表评论之前对这种方法有反馈。

you can use it while doing bootstrap like this 你可以在做这样的bootstrap时使用它

let nm = new Message(message);

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

and for this 并为此

EXCEPTION: Error: Uncaught (in promise): No provider for Http! 例外:错误:未捕获(承诺):没有Http的提供者! (ApiService -> Http) (ApiService - > Http)

in service create constructor and import the HTTP like this 在服务中创建构造函数并像这样导入HTTP

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

  constructor(private http: Http) {

  }
}

for this purpose 以此目的

Oh sorry, this is not how I want to use my class. 对不起,这不是我想要上课的方式。 For every message in the chat I'm making, I instantiate a Message. 对于我正在进行的聊天中的每条消息,我都会实例化一条消息。 I don't want just one global Message class but several Message objects. 我不想只有一个全局Message类,而是几个Message对象。

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

I solved it by using @Inject 我用@Inject解决了它

import { Inject } from "@angular/core;

and i think it should work like this 我认为它应该像这样工作

@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