【发布时间】:2016-08-05 02:04:23
【问题描述】:
我是第一次尝试 Angular2,但在创建服务时遇到了一些问题。实际上在使用该服务。我创建了以下数据服务
import {Injectable} from 'angular2/core';
import {recentActivity} from './app/components/recentActivity/model'
@Injectable()
export class RecentActivityDataService {
loadList() {
const items: Array<recentActivity> = [];
items.push({
url: 'From Service',
name: 'From Service'
});
return items;
}
}
然后在一个组件中我有以下内容:
import {Component, OnInit} from 'angular2/core';
import {recentActivity} from './model';
import {RecentActivityDataService} from './dataService';
@Component({
selector: 'recentActivity',
templateUrl: './app/components/recentActivity/recentActivity.html',
providers: [RecentActivityDataService]
})
export class RecentActivity implements OnInit {
items: Array<recentActivity> = [];
constructor(private dataService: RecentActivityDataService) {
}
ngOnInit() {
this.items = this.dataService.loadList();
}
}
当我启动此组件时,我收到以下错误消息
“未捕获(承诺中):无法解析所有参数 '近期活动'(?)。确保所有参数都被修饰 带有 Inject 或具有有效的类型注释和“RecentActivity” 用 Injectable 装饰。”
我不知道我在这里缺少什么,因为我的服务上有 @Injectable 并且在我的组件中我将它列为提供者。但是在构造函数中它仍然无法解决这个问题。
在 app.Component 我有以下内容
import {Component} from 'angular2/core';
import {StandardNavigation} from './navigation/standard';
import {RecentActivity} from './components/recentActivity/recentActivity';
@Component({
selector: 'cranalytics',
templateUrl: './app/main.html',
directives: [StandardNavigation, RecentActivity]
})
export class AppComponent {
}
我尝试了以下更改。在我的 Main 中,我正在引导 AppComponent: 引导程序(应用组件);
在 AppComponent 中,我将服务作为提供者放在那里
import {Component} from 'angular2/core';
import {StandardNavigation} from './navigation/standard';
import {RecentActivity} from './components/recentActivity/recentActivity';
import {RecentActivityDataService} from './components/recentActivity/dataService';
@Component({
selector: 'cranalytics',
templateUrl: './app/main.html',
directives: [StandardNavigation, RecentActivity],
providers: [RecentActivityDataService]
})
export class AppComponent {
}
在最近的活动中我已经导入了数据服务
import {Component, OnInit, Inject, forwardRef} from 'angular2/core';
import {recentActivity} from './model';
import {RecentActivityDataService} from './dataService';
@Component({
selector: 'recentActivity',
templateUrl: './app/components/recentActivity/recentActivity.html',
})
export class RecentActivity implements OnInit {
items: Array<recentActivity> = [];
constructor( private dataService: RecentActivityDataService) {
}
ngOnInit() {
this.items = this.dataService.loadList();
}
}
但这给了我同样的错误信息
【问题讨论】:
-
没有类请求
RecentActivity。错误来自其他地方。RecentActivity类型的构造函数参数在哪里? -
如果您引导服务而不是在组件上提供服务会发生什么?
-
在 App.Component 中,我添加了 import 行和 providers 行,并将它们从 RecentActivity 组件中删除,我得到了同样的错误。
-
我可以让它工作的唯一方法是如果(使用问题中列出的原始实现)是如果我在参数之前添加 @Inject(forwardRef(() => RecentActivityDataService))构造函数,但根据我所阅读的内容,我不应该这样做
-
或重新排序源文件中的类或将每个类移动到自己的文件中
标签: angular