使用 index.ts 文件导出类会导致注入的构造函数中未定义 [英] Using index.ts file to export class causes undefined in injected constructor

查看:21
本文介绍了使用 index.ts 文件导出类会导致注入的构造函数中未定义的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 index.ts 文件来封装 angular 2 样式指南中提到的导出(https://github.com/mgechev/angular2-style-guide/blob/master/old/README.md#directory-structure).
这在我编写的应用程序中运行良好,但由于某种原因,在我试图注入另一个服务的一个服务中,这会导致一个奇怪的错误.

Im using an index.ts file to encapsulate exports as mentioned in the angular 2 style guide (https://github.com/mgechev/angular2-style-guide/blob/master/old/README.md#directory-structure).
This worked fine across the app Im writing, but for some reason in one service that im trying to inject into another service this causes a strange Error.

导出的类:

import {Injectable} from "angular2/core";
@Injectable()
export class UserIds{
   private _signature_id:string;
   private _role_id:number;
   get signature_id():string{
      return this._signature_id;
   }
   set signature_id(id:string){
      this._signature_id = id;
   }
   get role_id():number{
      return this._role_id;
   }
   set role_id(id:number){
      this._role_id = id;
   }
}

index.ts 文件:

The index.ts file:

export {Midiate} from "./midiate.service/midiate.service";
export {HttpRest} from "./http_rest.service/http_rest.service";
export {UserIds} from "./user_ids.service/user_ids.service"

导致错误的代码(导入文件):

The code that caused the Error (the importing file):

import {UserIds} from "../index";
import {Http} from 'angular2/http';
@Injectable()
export class HttpRest{
 constructor(
    public _http: Http,
    public userIdsx: UserIds
 ){}
...
}

浏览器抛出的错误:

EXCEPTION: Cannot resolve all parameters for 'HttpRest'(Http, undefined). Make sure that all the parameters are decorated with Inject or have valid type annotations and that 'HttpRest' is decorated with Injectable.

如您所见,UserIds 类在构造函数的参数中未定义.

As you can see the UserIds class is undefined in the params of the constructor.

将 UserIds 导入更改为源文件修复了问题:

Changing the UserIds import to the source file fixed the problem:

import {UserIds} from "../user_ids.service/user_ids.service";

我仍然希望使用 index.ts 作为我的应用程序中的所有其他服务和组件来保持旧样式,并且还理解为什么会发生这种情况.

Still I want to keep the older style on this using the index.ts as all other services and components in my app, and also understand why did this happen.

推荐答案

看起来您在 index.ts 中放置导出的顺序很重要!不确定这是不是一个错误,但无论如何......

Looks like the order you put your exports in the index.ts does matter! Not sure if it's a bug or not but anyway...

用元数据修饰的类应该在 index.ts 的顶部.如果其中一个注入另一个,另一个"应该在一个"之上.

Classes decorated with metadata should be at the top of the index.ts If one of them injects another, the "another" should be above the "one".

这篇关于使用 index.ts 文件导出类会导致注入的构造函数中未定义的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆