runtimeZero
runtimeZero

Reputation: 28116

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 ?

Upvotes: 0

Views: 144

Answers (3)

runtimeZero
runtimeZero

Reputation: 28116

Apparently I was using typescript incorrectly.

Had to declare storageService as below:

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

i.e I was missing the private keyword

Upvotes: 0

Will.Harris
Will.Harris

Reputation: 4014

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.

Upvotes: 1

Günter Zöchbauer
Günter Zöchbauer

Reputation: 658067

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);
        });
    }
}

Upvotes: 0

Related Questions