【发布时间】:2017-02-08 08:58:56
【问题描述】:
我想在我的应用程序中创造出可注入的时刻。
我刚开始学习 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'.
【问题讨论】:
-
你经历过this answer吗?
-
不相关。我不想通过导入使用它。我希望能够在任何课程中注入它
-
你在使用
angular-cli吗? -
是的,我正在使用 cli
-
为什么要通过构造函数注入呢?是什么原因?