user6509972 user6509972 - 1 month ago 12
TypeScript Question

Assigning an import to a variable within a constructor

I am building an app in Ionic2. I want to implement Facebook within the app and so I am trying to use the ionic-native Facebook api. I imported it and then attempted to assign it to a variable so I could use the functions associated with it.

Here is my code.

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Facebook } from 'ionic-native';


@Component({
selector: 'page-news-feed',
templateUrl: 'news-feed.html',
})
export class NewsFeed {

fb: any;

constructor(public navCtrl: NavController, facebook: Facebook) {
this.fb = facebook;
}

doRefresh(refresher) {
console.log('Begin async operation', refresher);

setTimeout(() => {
console.log('Async operation has ended');
refresher.complete();
}, 2000);
}

this.fb.login([]);

ionViewDidLoad() {
console.log('Hello NewsFeed Page');
}

}


I thought an import works much like a class in that you can import it and assign it to a variable and then have access to its methods. Does it not work like that? How does it work?

Answer

You just have to import Facebook class like it is said in Ionic native docs : https://ionicframework.com/docs/v2/native/

You don't need to inject it through the constructor. As method are static this will print an error.

Be sure to also call Facebook after platform.ready event. And don't forget to add the plugin. See your example modified accordingly.

import { Component } from '@angular/core';
import { NavController, Platform } from 'ionic-angular';
import { Facebook } from 'ionic-native';


@Component({
  selector: 'page-news-feed',
  templateUrl: 'news-feed.html',
})
export class NewsFeed {

  constructor(public navCtrl: NavController, platform: Platform) {
    platform.ready().then(() => {
      console.log('Faceboook');
      Facebook.login([]).then((response) => {
        console.log(response);
      }).catch((error) => {
        console.error(error);
      });
    })
  }

    doRefresh(refresher) {
        console.log('Begin async operation', refresher);

        setTimeout(() => {
            console.log('Async operation has ended');
            refresher.complete();
        }, 2000);
    }

  ionViewDidLoad() {
    console.log('Hello NewsFeed Page');
  }

}
Comments