2017-03-03 45 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

单身服务方式不适合我以及寻找有关它的答案:) –