2017-03-03 25 views
0

任何人都知道如何使用Ionic2 v2.1.0創建angular2服務?Ionic V2 - 創建服務

已經嘗試了很多東西,但不斷收到錯誤。

我跟着從這裏How to use angular 2 service with Ionic 2一些答案,但它不工作...

這裏是我的代碼

DataBaseService.ts

import {Injectable} from "@angular/core"; 

@Injectable() 
export class DataBaseService { 
    constructor() { 
    } 

    execSQL() { 
     console.log('call works'); 
    } 
} 

進口的「app.component.ts 「

import { DataBaseService } from 'DataBaseService'; 

並把它放在」app.compone nt.ts」

@Component({ 
    templateUrl: 'app.html', 
    providers: [DataBaseService] 
}) 

如果我運行的應用程序就這樣,我得到以下錯誤

Uncaught Error: Cannot find module "DataBaseService" 
+0

DatabaseService的路徑是否正確? – MorKadosh

+0

你確定的路徑? –

+0

是的! DataBaseService.ts位於app.component.ts的相同路徑中! –

回答

1

如果服務文件是在同一位置做

import { DataBaseService } from './DataBaseService'; 

你是得到的錯誤,因爲它正在尋找一個模塊,當你直接給它作爲import { DataBaseService } from 'DataBaseService';

1

有關https://angular.io/styleguide將組件構造函數中的NgModule和它們添加到提供程序中。應用程序引導時應該初始化服務。

@NgModule({ 
imports: [MyModules] 
declerations: [MyComponent] 
providers: [MyService] 
}); 
+0

True ..但只有當你需要一個單例服務時...它可以在組件也是 –

+0

感謝您的幫助,suraj答案是正確的爲我的情況! –

+0

單身服務方式不適合我以及尋找有關它的答案:) –