在服务

时间:2018-02-27 14:45:31

标签: angular typescript ionic-framework ionic-native

我安装了Native Storage。所以我必须在home.ts(组件)上使用它。这是我的代码

  setStyle (val: string) {
    this.nativeStorage.setItem('style', {color: val})
    .then(
      () => console.log('Stored item!'),
      error => console.error('Error storing item', error)
    );
  }

  getStyle (property: string) {
    this.nativeStorage.getItem('style')
    .then(
      data => console.log(data[property]),
      error => console.error(error)
    );
  }

  ngOnInit() {
    this.setStyle('fff');
    this.getStyle('color');
  }

当我使用ionic cordova run browser运行我的应用时,我的代码效果很好。我在控制台中看到了这个

Stored item!
fff

但我的问题当我在style.ts(服务)使用原生存储时

import { NativeStorage } from '@ionic-native/native-storage';

export class Style {

  constructor(private nativeStorage: NativeStorage) {}

  set (val: string) {
    this.nativeStorage.setItem('style', {color: val})
    .then(
      () => console.log('Stored item!'),
      error => console.error('Error storing item', error)
    );
  }

  get (property: string) {
    this.nativeStorage.getItem('style')
    .then(
      data => console.log(data[property]),
      error => console.error(error)
    );
  }

}

并在home.ts(组件)

中使用我的服务
import { Component, OnInit } from '@angular/core';
import { Style } from '../../style/style';

export class HomePage implements OnInit{

  constructor(private style: Style) {}

  ngOnInit() {
    this.style.set('fff');
    this.style.get('color');
  }

}

我在控制台上出现了这个错误

Uncaught Error: Can't resolve all parameters for Style: (?).
    at syntaxError (compiler.js:466)
    at CompileMetadataResolver._getDependenciesMetadata (compiler.js:15547)
    at CompileMetadataResolver._getTypeMetadata (compiler.js:15382)
    at CompileMetadataResolver._getInjectableMetadata (compiler.js:15362)
    at CompileMetadataResolver.getProviderMetadata (compiler.js:15722)
    at compiler.js:15633
    at Array.forEach (<anonymous>)
    at CompileMetadataResolver._getProvidersMetadata (compiler.js:15593)
    at CompileMetadataResolver.getNgModuleMetadata (compiler.js:15161)
    at JitCompiler._loadModules (compiler.js:33542)

但是当我不使用构造函数时,我的代码工作

import { NativeStorage } from '@ionic-native/native-storage';

export class Style {

  set (val: string) {
    new NativeStorage().setItem('style', {color: val})
    .then(
      () => console.log('Stored item!'),
      error => console.error('Error storing item', error)
    );
  }

  get (property: string) {
    new NativeStorage().getItem('style')
    .then(
      data => console.log(data[property]),
      error => console.error(error)
    );
  }

}

我的问题是如何在构造函数中使用本机存储  并避免此错误Can't resolve all parameters for Style: (?)

1 个答案:

答案 0 :(得分:1)

您必须将标志@Injectable()放在服务类声明之上。

文档:Angular docs