简体   繁体   English

喷油嘴无法在Angular2 / Ionic2中正常工作

[英]Injector not working as expected in Angular2/Ionic2

I have defined a service as follows: 我已经定义了如下服务:

//storageService.ts
import { Injectable } from '@angular/core';
import {Storage, SqlStorage} from 'ionic-angular';

@Injectable()
export class StorageService {
    storage: any;

    constructor() {
        this.storage = new Storage(SqlStorage);
    }

    getUser() {
        return this.storage.get('user');
    }

}

I am injecting this in another Class as below: 我将其注入另一个类,如下所示:

Profile.ts
import {StorageService} from '../../services/storageService';

@Page({
    templateUrl: 'build/pages/profile/profile.html',
    providers: [StorageService]
})
export class ProfilePage {


    constructor(private http: Http, storageService: StorageService)  {
        this.storageService.getUser().then(user => {
          this.user = JSON.parse(user);  
        }).catch(error => {
           console.log(error);
        });

    }

}

However i keep receiving the error: 但是我一直收到错误:

Cannot read property 'getUser' of undefined

since I am injecting the service in the constructor..howcome I am getting this error ? 由于我将服务注入到构造函数中,所以我收到此错误?

Because you are using TypeScript you need to define the provider as private or public in the constructor and this will automatically create an instance of the provider within the page class, for example: 因为您正在使用TypeScript,所以需要在构造函数中将提供程序定义为privatepublic ,这将在页面类中自动创建提供程序的实例,例如:

constructor(private http: Http, private storageService: StorageService)  {
        this.storageService.getUser().then(user => {
          this.user = JSON.parse(user);  
        }).catch(error => {
           console.log(error);
        });    
    }

Other replies to your question provide the JavaScript solution which won't work for you. 对您问题的其他答复提供了JavaScript解决方案,该解决方案对您不起作用。

As far as I know you need a static parameters getter in Ionic like: 据我所知,您需要在Ionic中使用静态parameters ,例如:

@Page({
    templateUrl: 'build/pages/profile/profile.html',
    providers: [StorageService]
})
export class ProfilePage {

    static get parameters() {
      return [[Http], [StorageService]];
    }

    constructor(private http: Http, storageService: StorageService)  {
        this.storageService.getUser().then(user => {
          this.user = JSON.parse(user);  
        }).catch(error => {
           console.log(error);
        });
    }
}

Apparently I was using typescript incorrectly. 显然我没有正确使用打字稿。

Had to declare storageService as below: 必须声明如下的storageService:

constructor(private http: Http,private storageService: StorageService)  {

ie I was missing the private keyword 即我错过了私人关键字

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM