简体   繁体   中英

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:

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.

As far as I know you need a static parameters getter in Ionic like:

@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:

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

ie I was missing the private keyword

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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