【问题标题】:Inject service in a simple class constructor with Angular2使用 Angular2 在简单的类构造函数中注入服务
【发布时间】: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


    【解决方案1】:

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

    这正是我一直想知道的;如果你真的需要在你的代码中调用一个构造函数并且仍然需要在你的类中注入一些东西怎么办?例如 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 并创建新的 Messages 实例:

    export class MessageExampleComponent {
      constructor(private messageFactory: MessageFactory) {}
    
      makeMessageDoSomethingWithService(): {
        let message = this.messageFactory.build({just: 'an', example: 'here'})
        message.doSomethingWithService();
      }
    }
    

    我不确定将其称为 MessageFactory 是否是一个正确的术语,但我想在某些版主删除此帖子而不发表评论之前获得有关此方法的反馈。

    【讨论】:

      【解决方案2】:

      你可以像这样在引导时使用它

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

      【讨论】:

      • 哦,抱歉,这不是我想要使用我的课程的方式。对于聊天中的每条消息,我都会实例化一个Message。我不想要一个全局 Message 类,而是几个 Message 对象。
      【解决方案3】:

      我使用 @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;
              }
      }
      

      【讨论】:

      • 完美。谢谢!
      • 我的错。在我使用未定义的 this.api 之前它一直有效。我不确定如何使用 @Inject() 装饰器。最后,我应该像这样在构造函数中传递 ApiService:new Message(message, this.api) 还是 ApiService 将被注入而不在构造函数参数中传递它?
      • 是的,它应该在构造函数中,所以当你使用 apiservice 时,你可以得到 http
      • 我的构造函数看起来像这个构造函数(message: any, @Inject(ApiService) api) { this.api = api; this.timestamp = message.timestamp; this.message = message.message;我不太确定如何使用 @Inject() :/
      • 如果这是你的消息类然后做这个构造函数(message: any, @Inject(ApiService) api:ApiService) { this.api = api; this.timestamp = message.timestamp; this.message = message.message; }
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-12-15
      • 2020-11-09
      • 2020-06-03
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多