2016-01-29 61 views
2

基本上我通過引用Angular2快速入門教程創建了一個示例應用程序。爲了進一步挖掘,我創建了./services/dataService.ts服務文件,如下所示。在Angular2中導入依賴項時遇到困難

import {Injectable} from 'angular2/core'; 
@Injectable() 
export class DataService { 
    items: Array<number>; 
    constructor() { 
     this.items = [1, 2, 3, 4]; 
    } 
    getItems() { 
     return this.items; 
    } 
} 

我在tsconfig其中以下路徑transpile app.ts & dataService.ts所提到"outDir": "../wwwroot/app",選項。

--wwwroot 
|app 
    |--app.js 
    |--services 
     |-- dataService.js 

MyAppComponent

import {Component, View, Inject, forwardRef} from 'angular2/core'; 
import {NgFor} from 'angular2/common'; 
import {bootstrap} from 'angular2/platform/browser'; 
import {DataService} from './services/dataService'; 

@Component({ 
    'selector': 'my-app', 
    template: ` 
      <div *ngFor="#item of items"> 
       {{item}} 
      </div> 
     `, 
    directives: [NgFor], 
    providers: [DataService] 
}) 
export class MyAppComponent { 
    items: Array<number>; 
    constructor(service: DataService) { 
     this.items = service.getItems(); 
    } 
} 
bootstrap(MyAppComponent) 

代碼獲取無錯編譯,但經過RAN應用我 以下錯誤,http://localhost:8413/app/services/dataService

無法加載資源:服務器與404狀態(未找到)

我用下面的代碼從index.html加載頁面上的應用程序文件作出迴應。

System.config({ packages: { src: { defaultExtension: 'js' } } }); 
System.import('app/app.js').then(null, console.error.bind(console)); 

我的問題是我怎麼能導入dataService.js,爲什麼是在一個地方給404錯誤還是它的存在?我研究了這個問題,但沒有發現任何有用的東西。任何幫助將不勝感激。

編輯

新增.tsconfig直接得到糾正時,有問題

{ 
    "compilerOptions": { 
    "noImplicitAny": false, 
    "noEmitOnError": true, 
    "module": "commonjs", 
    "removeComments": false, 
    "sourceMap": true, 
    "target": "es5", 
    "outDir": "../wwwroot/app", 
    "experimentalDecorators": true, 
    "emitDecoratorMetadata": true 
    }, 
    "exclude": [ 
    "node_modules", 
    "wwwroot" 
    ] 
} 
+0

是文件所在的'/ app/services/dataservice'? –

+0

@MarkPieszak沒有運氣:(現在它不允許我構建應用程序.. –

+0

似乎不是一個角度問題。建議您發佈您的gulp文件,js在另一個帖子中被標記爲 –

回答

0

的問題是與System配置,以前我在下面的代碼加載組件。

System.config({ packages: { src: { defaultExtension: 'js' } } }); 
System.import('app/app.js').then(null, console.error.bind(console)); 

基本上System.config設置告訴packages是屬於src文件夾和文件defaultExtensionjs。所以我將packagessrc更改爲app,因爲我的文件夾是app,而不是src

除此之外,我將System.import('app/app.js')更改爲System.import('app/app'),因爲文件的默認擴展名是js,所以我不需要爲此煩惱。所以我的組件加載腳本更改爲下面。

System.config({ packages: { app: { defaultExtension: 'js' } } }); 
System.import('app/app').then(null, console.error.bind(console));