angularjs - 使力矩可注入(inject)angular2

标签 angularjs angular

我想花时间在我的应用程序中进行注入(inject)。
我刚开始学习 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'.

最佳答案

Moment 本身并不是 Angular2 的可注入(inject)对象。但是它可以包裹在一个里面。

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

不完美,但有效。

关于angularjs - 使力矩可注入(inject)angular2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39780378/

相关文章:

javascript - ng-view 导致页面崩溃

angular - owl-carousel 不适用于带有 html 模板的 Angular *ngfor 循环

javascript - 将外部库导入到 Angular 2 (Systemjs)

javascript - AngularJS - $watch 和 $timeout

javascript - 如何删除 Angular $modal 缓存?

angularjs - 将自定义服务注入(inject) ui-router 配置会引发错误 : Unknown provider: [Service]

javascript - 如何在未完成添加序列的情况下从 rxjs 创建数组

javascript - 使用 Angular 形式将元素值形成为 JSON

javascript - 在使用 Angular 删除文件时选择所有复选框时出现问题

javascript - 在单页应用程序中选择菜单时调用 Controller - angularJs