我第一次嘗試Angular2,並在創建服務時遇到一些問題。其實在使用該服務。我曾經在一個組件創建了以下數據服務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();
}
}
當我拉這個組件我收到以下錯誤消息
「未捕獲(承諾):無法解析 'RecentActivity'(?)的所有參數。確保所有參數均使用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 {
}
我曾嘗試以下變化。在我的主要我bootstrapping AppComponent: bootstrap(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'類型的構造函數參數? –
如果您啓動服務而不是在組件上提供服務,會發生什麼情況? – Harangue
查看更新的消息 –