【问题标题】:Correct way to import Horizon IO into angular 2 project将 Horizo​​n IO 导入 Angular 2 项目的正确方法
【发布时间】:2017-09-18 22:51:20
【问题描述】:

我目前将 Horizo​​nIO 导入 Angular 2 项目的方式如下:

var horizon = require('@horizon/client');

@Injectable()
export class DbService {
    private horizon;

    constructor() {
        this.horizon = Horizon({host: 'localhost:8181'});
    }
}

现在我觉得这不是正确的方法,因为我应该能够做到

import { Horizon } from '@horizon/client';

虽然没有抛出错误,但变量不可用。

想法/cmets?

【问题讨论】:

    标签: angular typescript horizon


    【解决方案1】:

    ES6 导入等价于

    var Horizon = require('@horizon/client');
    

    是

    import * as Horizon from '@horizon/client';
    

    你所做的相当于

    var Horizon = require('@horizon/client').Horizon;
    

    编辑:

    我现在使用以下代码来使地平线可注入:

    import { Injectable } from '@angular/core';
    import * as Hz from '@horizon/client';
    
    @Injectable()
    export class Horizon extends Function {
      private _hz;
    
      constructor() {
        super('...args', 'return this._hz(...args)');
        this._hz = new Hz({host: 'localhost:8181'});
    
        return this.bind(this);
      }
    }
    

    然后可以像直接导入它时一样注入和调用它:

    constructor(hz: Horizon){
      hz('messages').watch().subscribe(...);
    }
    

    不完全确定这是否比直接导入 Horizo​​n 有什么好处,但使用 DI 感觉更加棱角分明。

    【讨论】:

    • 谢谢,import * as Horizo​​n from '@horizo​​n/client' 确实是正确的
    【解决方案2】:

    检查@horizon/client 是否在您的node_modules 文件夹中,如果没有:尝试npm install (https://www.npmjs.com/package/@horizon/client)。

    【讨论】:

    • @horizo​​n/client 存在于我的 node_modules 文件夹中
    • @woodsprite 尝试在你的组件的构造函数中导入它:比如constructor(public horizon: Horizon){}
    • 一开始我以为它可以工作,但它抛出:“错误:无法解析服务的所有参数”
    • 也许可以试试:constructor(@Inject(Horizon horizon: Horizon) 和 import { Inject } from '@angular/core ?
    • 我非常感谢您的努力,但到目前为止没有任何效果,幸运的是这没什么大不了的,我只是在寻求最佳实践理由
    猜你喜欢
    • 2016-11-15
    • 1970-01-01
    • 2023-03-22
    • 1970-01-01
    • 1970-01-01
    • 2016-11-30
    • 1970-01-01
    • 1970-01-01
    • 2018-08-24
    相关资源
    最近更新 更多