使角度2可注射

时间:2016-09-29 21:33:15

标签: angularjs angular

我想通过我的应用程序注入时间 我刚刚开始学习ng2,但在文档中找不到这种用法 以下是我在app.module.ts中的内容:

import {BrowserModule} from '@angular/platform-browser';
import {NgModule} from '@angular/core';
import {FormsModule} from '@angular/forms';
import {HttpModule} from '@angular/http';
import {AppComponent} from './app.component';
import * as moment from 'moment';

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [{provide: 'moment', useValue: moment}],
  bootstrap: [AppComponent]
})
export class AppModule {
}

这是组件:

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.sass']
})


export class AppComponent {
  title = 'app works!';

  constructor(private moment) {
    this.title += this.moment;
  }
}

出现此错误:

Uncaught Error: Can't resolve all parameters for AppComponent:

如何正确完成?

更新的模块

const moment = new OpaqueToken('moment');

@NgModule({
  declarations: [
    AppComponent
  ],
  imports: [
    BrowserModule,
    FormsModule,
    HttpModule
  ],
  providers: [{provide: moment, useValue: moment}],
  bootstrap: [AppComponent]
})

export class AppModule {
}

更新的组件

import { Component } from '@angular/core';
import * as moment from 'moment';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.sass']
})


export class AppComponent {
  title = 'app works!';

  constructor(private moment: moment) {
    this.title += this.moment()
  }
}

此行constructor(private moment: moment)出现错误,告知:Cannot find name 'moment'.

6 个答案:

答案 0 :(得分:3)

您需要使用OpaqueToken,这将允许您创建基于字符串的令牌。我建议您更改moment的名称,以避免与库的moment变量发生冲突。

// You can place this is some file, so that you can export it.
export const Moment = new OpaqueToken('moment');

然后你可以使用

providers: [{provide: MomentStatic, useClass: moment}],

您可以浏览this article了解更多详情

虽然使用依赖项将其包含在Component构造函数中。

constructor(private moment: MomentStatic)

答案 1 :(得分:2)

瞬间本身不是Angular2的注射剂。但它可以包裹在一个内部。

Plunker Demo

<强> moment.service.ts

import { Injectable } from '@angular/core';
import * as m from 'moment';
@Injectable()
export class MomentService {
    moment = m;
}

<强> app.module.ts

import { MomentService } from './moment.service';

@NgModule({
    providers: [MomentService]
    ...

<强> app.component.ts

import { MomentService } from './moment.service';

export class AppComponent {
    constructor(private ms: MomentService){
        console.log('Moment:' + this.ms.moment("20111031", "YYYYMMDD").toString());
    }
}

不完美,但有效。

答案 2 :(得分:0)

不必注入瞬间,它是一个可以“使用”的库。现在您可以使用时刻的功能,将它导入您的打字稿文件就足够了。

答案 3 :(得分:0)

如果您正在加载moment.js,那么全局可以使用服务包装它,然后您可以在整个应用程序中注入它?

import {Moment} from '../../node_modules/moment';

import { Injectable } from '@angular/core';

declare var moment: any;

@Injectable()
export class MomentService {
    constructor() { }

    get(): Moment {
        return moment;
    }
}

我通过这种方式在编码时获得TS IntelliSense(至少我在VSCode中),您也可以轻松处理模拟时刻。

答案 4 :(得分:0)

我找到的最佳解决方法是创建一个包装器服务,但也使用getter直接在服务本身上公开一些最常用的方法:

import { Injectable } from '@angular/core';
import * as moment from 'moment';

/**
 * A wrapper for the moment library
 */
@Injectable()
export class MomentService {
  /**
   * Creates and returns a new moment object with the current date/time
   */
  public moment() { return moment(); }

  // expose moment properties directly on the service
  public get utc() { return moment.utc; }
  public get version() { return moment.version; }
  public get unix() { return moment.unix; }
  public get isMoment() { return moment.isMoment; }
  public get isDate() { return moment.isDate; }
  public get isDuration() { return moment.isDuration; }
  public get now() { return moment.now; }
}

答案 5 :(得分:0)

现在不确定这是否有帮助,但您需要与以下相似的内容(未经测试)才能使其在您的服务中发挥作用。

import { Inject } from '@angular/core';

constructor(@Inject(moment) private moment) {
    this.title += this.moment()
  }

关键位是 @Inject

相关问题