I have a provider having a method getWeather() and I want to call it from home component. When I am trying to call getWeather() from home component I am getting error in console like: ERROR TypeError: Cannot read property 'getWeather' of undefined
weather.ts
import { Http } from '#angular/http';
import { Injectable } from '#angular/core';
import "rxjs/add/operator/map";
#Injectable()
export class WeatherProvider {
constructor(public http: Http) {
console.log('Hello WeatherProvider Provider: ');
}
getWeather() {
return this.http.get('https://samples.openweathermap.org/data/2.5/forecast?q=London,us&appid=b6907d289e10d714a6e88b30761fae22').map(res=>res.json());
}
}
home.ts
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { WeatherProvider } from "../../providers/weather/weather";
//import { HttpModule } from "#angular/http";
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
weather:any;
constructor(public navCtrl: NavController, private wp:WeatherProvider) {
}
ionViewWillEnter() {
this.weather.getWeather().subscribe(weather=>{
console.log(weather)
})
}
}
The error is gone after restarting the ionic dev server. I don't know why the ionic is behaving like this.
I created a brand new Ionic project to run this code. It worked fine in Postman but when I run ionic serve I get an error.
home.ts :
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { Http, Headers, RequestOptions, HttpModule } from '#angular/http';
import 'rxjs/Rx';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/do';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
restaurants: any;
constructor(public navCtrl: NavController, public http: Http) {
var headers = new Headers();
headers.append('Authorization', 'Bearer XX');
var options = new RequestOptions({headers: headers});
this.http.get('https://api.yelp.com/v3/businesses/search?latitude=XX&longitude=XX&radius=10000&categories=food&locale=en_NZ', options).map(res => res.json()).subscribe(data => {
this.restaurants = data.data.children;
console.log(this.restaurants);
});
}
}
When I run ionic serve, I see the following error in the console:
For ionic serve you may use Chrome plugin: https://chrome.google.com/webstore/detail/allow-control-allow-origi/nlfbmbojpeacfghkpbjhddihlkkiljbi?hl=en or any other.
In any case you will need also to add Yelp API address to your index.html to deal with CSP.
See information about CSP here: https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-whitelist/
I am trying to execute file transfer from a Flask server to an Ionic3 application. Basically, what I want to do is send a .vcf file from the server to the application to them be read and displayed in the application. The application does not need to store the file in any form of persistent memory.
When I try to do this, I get a ton of error. The one I am encountering right now is:
Encountered undefined provider! Usually this means you have circular dependencies (might be caused by using 'barrel' index.ts files.
I tried making a whole separate provider file for file-transfer but that just gave me other errors. Currently, my .ts file that is throwing the error is as follows:
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { Transfer, TransferObject } from '#ionic-native/file-transfer';
import { File } from '#ionic-native/file';
#IonicPage()
#Component({
selector: 'page-quiz',
templateUrl: 'quiz.html',
providers: [Transfer, TransferObject, File]
})
export class QuizPage {
storageDirectory: string = '';
constructor(public navCtrl: NavController, public navParams: NavParams,
private transfer: FileTransfer, private file: File) {
this.vCardDownload("b734cdc8-8ec1-4fde-b918-b6062b5099df");
}
ionViewDidLoad() {
console.log('ionViewDidLoad QuizPage');
}
vCardDownload(uuid) {
const fileTransfer: TransferObject = this.transfer.create();
const vCardLocation = 'http://xxxxxxx.xxx.edu:5000/get_question_vCard?uuid=' + uuid;
fileTransfer.download(vCardLocation, this.file.applicationDirectory + uuid).then((entry) => {
console.log("file was downloaded", entry.toURL());
alertSuccess.present();
}, (error) => {
console.log("ERROR file was not downloaded");
});
}
}
Where am I going wrong here and how can I achieve file transfer? I think I am on the right track to getting it working -- I am pretty new to typescript and mobile development so I apologize in advance for any mistakes. Essentially I want to "capture the file within the application."
It turns out I had two errors. First, my import statements were wrong. Second, I didn't add certain imports to the providers listing in my app.module.ts file.
Here are my providers in app.module.ts:
import { File } from '#ionic-native/file';
import { FileTransfer } from '#ionic-native/file-transfer';
... declarations, imports, etc. ...
providers: [
StatusBar,
SplashScreen,
File,
FileTransfer,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
Here is the sample code I used to download the .vcf file.
import { FileTransfer, FileTransferObject } from '#ionic-native/file-transfer';
import { File } from '#ionic-native/file';
...
constructor(public navCtrl: NavController, public navParams: NavParams,
private transfer: FileTransfer, private file: File) {
this.vCardDownload("XXXXXX-XXXXX-XXXX-XXXX");
}
...
vCardDownload(uuid) {
console.log("Trying to download vCard!");
const fileTransfer: FileTransferObject = this.transfer.create();
const vCardLocation = 'http://XXXXXX.XXX.edu:5000/get_question_vCard?uuid=' + uuid;
fileTransfer.download(vCardLocation, this.file.dataDirectory + 'file.vcf').then((entry) => {
console.log('download complete: ' + entry.toURL());
}, (error) => {
console.error(error);
});
}
Note that so far this only works for me on a mobile device.
My parent component is too large to manage so I want to move the the functions into the separated child classes that extend the parent.
The parent class contains variables that need to be updated in the child classes as well as I have injected providers into the parent as well.
#Component({
selector: 'events-list',
templateUrl: 'events-list.html'
})
export class EventsListComponent {
filterString: string;
infiniteScroll: any;
refresher: any;
eventsList: any[];
selectedCategoriesList: [Category];
pageNum: number;
pageSize: number;
searchText: string = '';
noEvents: boolean;
filterSearchText: string;
filterStartDate: string;
filterEndDate: string;
tabsFilterValue: string = 'all'
constructor(
public authSrvc: AuthSrvc,
public calendarSrvc: CalendarSrvc,
public eventsSrvc: EventsSrvc,
public helperSrvc: HelperSrvc,
public locationSrvc: LocationSrvc,
public pushSrvc: PushSrvc) {
}
Above is my parent class
import {Injectable} from '#angular/core';
import {Response} from '#angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/timeout';
import 'rxjs/add/observable/of';
import {Observable} from 'rxjs/Observable';
import {ModalController, LoadingController, NavController, ToastController, Platform} from 'ionic-angular';
import {Storage} from '#ionic/storage';
import {DateFormatPipe} from 'angular2-moment';
import {Category} from '../../../app/app.interfaces';
import * as moment from 'moment';
/** Ionic Native **/
import {GoogleAnalytics} from '#ionic-native/google-analytics';
import {Network} from '#ionic-native/network';
/** Providers **/
import {AuthSrvc} from '../../../../providers/auth-srvc';
import {CalendarSrvc} from '../../../../providers/calendar-srvc';
import {EventsSrvc} from '../../../../providers/events-srvc';
import {HelperSrvc} from '../../../../providers/helper-srvc';
import {LocationSrvc} from '../../../../providers/location-srvc';
import {PushSrvc} from '../../../../providers/push-srvc';
/** Pages **/
import {AuthPage} from '../../../pages/auth/auth-page';
import {EventsListComponent} from '../../../events-components/events-list/events-list';
export class eventsInit extends EventsListComponent {
constructor(
loadingCtrl: LoadingController,
toastCtrl: ToastController,
modalCtrl: ModalController,
navCtrl: NavController,
platform: Platform,
storage: Storage,
ga: GoogleAnalytics,
network: Network,
authSrvc: AuthSrvc,
calendarSrvc: CalendarSrvc,
eventsSrvc: EventsSrvc,
helperSrvc: HelperSrvc,
locationSrvc: LocationSrvc,
pushSrvc: PushSrvc
) {
super(loadingCtrl,
toastCtrl,
modalCtrl,
navCtrl,
platform,
storage,
ga,
network,
authSrvc,
calendarSrvc,
eventsSrvc,
helperSrvc,
locationSrvc,
pushSrvc);
}
ngOnInit()
{
console.log('test')
}
}
Above is my child class
this is not working and is always failing with by parameters not being populated or the super call failing. What is the correct way to do this.
/** Update **/
If removing the injectable I always get the error Can't resolve all parameters for eventsInit: (?, ?, ?, ?, ?, ?).
Below is my main module
import {NgModule, ErrorHandler} from '#angular/core';
import {FormsModule} from '#angular/forms';
import {Ng2ImgFallbackModule} from 'ng2-img-fallback';
import {CloudSettings, CloudModule} from '#ionic/cloud-angular';
import {MomentModule,DateFormatPipe} from 'angular2-moment';
import { IonicStorageModule } from '#ionic/storage';
import {IonicApp, IonicModule, IonicErrorHandler} from 'ionic-angular';
import {EnvironmentsModule} from '../environment_variables/environment_variables.module'
import {AppConfig} from '../app/app.config';
import {MyApp} from '../app/app.component';
/** Ionic Native **/
import {Calendar} from '#ionic-native/calendar';
import { Diagnostic } from '#ionic-native/diagnostic';
import {Facebook} from '#ionic-native/facebook';
import {GooglePlus} from '#ionic-native/google-plus';
import { GoogleAnalytics } from '#ionic-native/google-analytics';
import { Keyboard } from '#ionic-native/keyboard';
import { LaunchNavigator, LaunchNavigatorOptions } from '#ionic-native/launch-navigator';
import {Network} from '#ionic-native/network';
import { SocialSharing } from '#ionic-native/social-sharing';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
/** Pages **/
import {AuthPage} from '../pages/auth/auth-page';
import {EventsPage} from '../pages/events/events-page';
import {EventPage} from '../pages/event/event-page';
import {ProfilePage} from '../pages/profile/profile';
import {SettingsPage} from '../pages/settings/settings';
/** Components **/
//Auth
import {LoginComponent} from '../components/auth-components/login/login';
import {ForgotPasswordDirective} from '../components/auth-components/forgot-password';
import {RegisterComponent} from '../components/auth-components/register/register';
import {SocialComponent} from '../components/auth-components/social/social';
import {WalkthroughComponent} from '../components/auth-components/walkthrough/walkthrough';
//Base
import {SidenavComponent} from '../components/sidenav/sidenav';
import {TimeslotFilterComponent} from '../components/timeslot-filter/timeslot-filter';
import {SettingsComponent} from '../components/settings/settings';
import {EventBookComponent} from '../components/event-book/event-book';
//Events
import {EventsFilterComponent} from '../components/events-components/events-filter/events-filter';
import {EventsListComponent} from '../components/events-components/events-list/events-list';
/** Events Extensions **/
import {eventsInit} from '../components/events-components/events-list/extensions/events-init';
import {EventsItemComponent} from '../components/events-components/events-item/events-item';
//Event
import {AttendeesListComponent} from '../components/event-components/attendees-list/attendees-list';
import {AttendeesItemComponent} from '../components/event-components/attendees-item/attendees-item';
//Profile
import {ProfileComponent} from '../components/profile/profile';
import {ParallaxHeaderDirective} from '../components/parallax-header';
/** Providers **/
import {EventsSrvc} from '../providers/events-srvc';
import {AuthSrvc} from '../providers/auth-srvc';
import {CalendarSrvc} from '../providers/calendar-srvc';
import {HelperSrvc} from '../providers/helper-srvc';
import {LocationSrvc} from '../providers/location-srvc';
import {PushSrvc} from '../providers/push-srvc';
/** Pipes **/
import {LimitToPipe} from '../pipes/limitTo'
const cloudSettings: CloudSettings = {
'core': {
'app_id': 'df0d4e63'
}
};
class NetworkMock extends Network {
get type(): string {
return (super['type'] === null) ? "wifi" : super['type'];
}
}
#NgModule({
declarations: [
MyApp,
AuthPage,
LoginComponent,
ForgotPasswordDirective,
ParallaxHeaderDirective,
RegisterComponent,
SocialComponent,
WalkthroughComponent,
SidenavComponent,
EventsPage,
EventsListComponent,
eventsInit,
EventsItemComponent,
EventsFilterComponent,
AttendeesListComponent,
AttendeesItemComponent,
EventPage,
ProfilePage,
ProfileComponent,
SettingsPage,
SettingsComponent,
TimeslotFilterComponent,
EventBookComponent,
LimitToPipe,
],
imports: [
IonicModule.forRoot(MyApp,
{
backButtonText: 'Back',
backButtonIcon: 'arrow-back',
iconMode: 'md',
modalEnter: 'modal-slide-in',
modalLeave: 'modal-slide-out',
tabsPlacement: 'bottom',
pageTransition: 'md',
mode: 'md'
}),
IonicStorageModule.forRoot(),
CloudModule.forRoot(cloudSettings),
FormsModule,
MomentModule,
EnvironmentsModule,
Ng2ImgFallbackModule
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
AuthPage,
EventsPage,
EventPage,
ProfilePage,
SettingsPage,
EventBookComponent,
EventsFilterComponent,
SidenavComponent
],
providers: [{provide: ErrorHandler, useClass: IonicErrorHandler},
Calendar,
Diagnostic,
Facebook,
GooglePlus,
DateFormatPipe,
GoogleAnalytics,
Keyboard,
LaunchNavigator,
{ provide: Network, useClass: NetworkMock },
SocialSharing,
StatusBar,
SplashScreen,
EventsSrvc,
AuthSrvc,
CalendarSrvc,
HelperSrvc,
EventsSrvc,
LocationSrvc,
AppConfig]
})
export class AppModule {
}
I think you have to follow below mentioned implementation.I have implemented this in my app and it is working fine.
Note: This is just a structure.Please implement it as you wish.
your component class:
import { eventsInit } from "../../path-for-it";
export class EventsListComponent extends eventsInit {
constructor() {
super();
}
Base class:
export abstract class eventsInit {
protected YourMethodName(res: Response) {
}
}
Update:
It seems you have not followed the latest changes of provider implementation.You have to declare it inside the app.module.ts file.Please see this article: Providers
So after banging the extend class logic into my head and understanding that it wasnt the correct way to break up my code. I went with an attribute based directives with #Hostlistener and #Input variables.
I was able to break up the parent component into much smaller sections and allow the parent component to hold all the variables and pass the updated values to the directives. I went from 1 component over 500 lines to multiple that dont go over 120. Much easier to read, to test and to maintain.
I'm trying to use filetransfer as a provider in my app, but I'm getting this problem.
"No provider for Transfer!"
I can't find the solution.
This is my code.
My provider
import { Injectable } from '#angular/core';
import { Transfer, FileUploadOptions, TransferObject } from '#ionic-native/transfer';
// import { File } from '#ionic-native/file';
#Injectable()
export class FileTransfer {
options: FileUploadOptions = {}
fileTransfer: any;
constructor(private transfer: Transfer) {
console.log('Hello FileTransfer Provider');
}
I already imported my provider to the app.module
import { NgModule, ErrorHandler } from '#angular/core';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { FileTransfer } from "../providers/file-transfer";
And added it to my providers in the same app.module
providers: [{ provide: ErrorHandler, useClass: IonicErrorHandler }, Storage, FileTransfer]
And finally, I'm importing the provider to my page.
import { Component } from '#angular/core';
import { FileTransfer } from '../../providers/file-transfer';
----
constructor(
public navCtrl: NavController,
public navParams: NavParams,
public storage: Storage,
public platform: Platform,
public alertCtrl: AlertController,
public modal: ModalController,
public loadingCtrl: LoadingController,
public fileTransfer: FileTransfer
)
So i dont know, where the problem is, I hope, you can help me.
Thanks!!
Try:
import { Transfer } from "../providers/file-transfer";
in your app.module.
And,
providers: [{ provide: ErrorHandler, useClass: IonicErrorHandler }, Storage, Transfer]
in your providers.
The error is
"No provider for Transfer!"
Your import syntax is for ionic-native 2.8.1 here.
Change import to
import { Transfer} from '#ionic-native';
Or change ionic-native version to 2.8.1.