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/
Related
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.
In an Ionic project i am using the code below to load a document collection from Firestore with the AngularFirestore wrappers.
Now that the content starts loading when the view was initialized i'm experiencing a delay by about 4-8 seconds until the firestore fetched data renders in my list-view, which is very very bad for the overall userexperience.
with the code below i'm able to show a loading spinner when the content starts loading bit i need it to stop showing the loader.
I have no clue how to trigger that event? Any help would be appreciated
thank you very much
import { City } from './../../model/City';
import { Component, AfterViewInit } from '#angular/core';
import { NavController, IonicPage, LoadingController } from 'ionic-angular';
import { AngularFirestore, AngularFirestoreCollection } from 'angularfire2/firestore';
import { Observable } from 'rxjs/Observable';
#IonicPage()
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage implements AfterViewInit {
citiesRef: AngularFirestoreCollection<City>
cities: Observable<City[]>;
loading = this.loadingCtrl.create({
content: 'Loading Regions...'
});
constructor(private loadingCtrl: LoadingController, private afs: AngularFirestore, public navCtrl: NavController) {
}
ngAfterViewInit(){
this.loading.present().then(()=>{
this.citiesRef = this.afs.collection<City>('regions', ref => ref.orderBy('name'));
this.cities = this.citiesRef.valueChanges();
})
}
}
Well, what I did was I subscribe to the this.cities. It worked in my case. The idea is it will fire loading.dismiss() once it is able to subscribe. Hope that helps
let loading = this.loadingCtrl.create({
content: 'Please wait...'
});
loading.present();
this.citiesRef=this.afs.collection('cities');
this.cities=this.citiesRef.valueChanges();
this.cities.subscribe(_=>{
loading.dismiss();
})
Followed the content of the url to implement dynamic menu items using JSON file stored under /assets/data. The menu is working fine with stored JSON file. Now I need to dynamically retrieve the JSON of same format in real time from a Salesforce API and display its content.
Can someone please suggest what changes I need to make here? should the json path in getMainMenu() method be replaced with the actual Saleforce API?
Below is the data-service.ts
import { Injectable } from '#angular/core';
import { Http, Response } from '#angular/http';
import 'rxjs/add/operator/map';
/*
Generated class for the DataServiceProvider provider.
See https://angular.io/guide/dependency-injection for more info on providers
and Angular DI.
*/
#Injectable()
export class DataServiceProvider {
constructor(public http: Http) {
console.log('Hello DataServiceProvider Provider');
}
getMainMenu(){
return this.http.get('assets/data/mainmenu.json')
.map((response:Response)=>response.json().Categories);
}
}
and app.component.ts
import { Component, ViewChild } from '#angular/core';
import { Nav, Platform } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { HomePage } from '../pages/home/home';
import { ListPage } from '../pages/list/list';
import { DataServiceProvider } from '../providers/data-service/data-service'
#Component({
templateUrl: 'app.html'
})
export class MyApp {
#ViewChild(Nav) nav: Nav;
rootPage: any = HomePage;
pages: any[]; //Array<{title: string, component: any}>;
mainmenu: any[];
constructor(public platform: Platform, public statusBar: StatusBar, public splashScreen: SplashScreen, public dataService: DataServiceProvider) {
this.initializeApp();
this.dataService.getMainMenu().subscribe((Response)=>{
this.mainmenu = Response;
console.log(this.mainmenu);
});
// used for an example of ngFor and navigation
this.pages = [
{ title: 'Home', component: HomePage },
{ title: 'List', component: ListPage }
];
}
initializeApp() {
this.platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
this.statusBar.styleDefault();
this.splashScreen.hide();
});
}
openPage(page) {
// Reset the content nav to have just this page
// we wouldn't want the back button to show in this scenario
this.nav.setRoot(page.component);
}
toggleSection(i) {
this.mainmenu[i].open = !this.mainmenu[i].open;
};
toggleItem(i,j) {
this.mainmenu[i].SubCategories[j].open = !this.mainmenu[i].SubCategories[j].open;
};
}
It looks like you will need to update the url in the getMainMenu method to that of your api. There might be some other changes you will need to make, such as adding authentication headers, but if the data coming from the api is the same as whats stored in the assets folder, your component shouldn't care "where" the data comes from.
I have been working on a project in Ionic and after running the file I got the the runtime error saying Cannot find module "../signup/signup". I then went into the project and checked to see if it the file and directory existed which it didn't. I then proceeded to create a directory and file to see if that would fix the problem and it did not. Here is the code for signup.ts
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
#Component(
{
templateUrl: 'signup.html'
})
export class SignupPage
{
static get parameters()
{
return [[NavController]];
}
constructor(public nav)
{
this.nav = nav;
}
}
Here is the page that I have made the import
import {Component} from '#angular/core';
import {NavController, AlertController} from 'ionic-angular';
import {SignupPage} from '../signup/signup';
import {TabsPage} from "../tabs/tabs";
import {FormBuilder, FormControl, FormGroup, AbstractControl, Validators, NgControl} from '#angular/forms';
import {AuthService} from '../../providers/auth-service';
#Component({
selector: 'page-login',
templateUrl: 'login.html'
})
export class LoginPage {
loginForm: FormGroup;
submitAttempt: boolean = false;
constructor(public navCtrl: NavController, public fb: FormBuilder, private _auth: AuthService, private alertCtrl: AlertController) {
this.loginForm = this.fb.group({
email: ['', Validators.compose([Validators.required, Validators.pattern('^[a-z0-9]+(\\.[_a-z0-9]+)*#[a-z0-9-]+(\\.[a-z0-9-]+)*(\\.[a-z]{2,15})$')])],
password: ['', Validators.compose([Validators.required, Validators.minLength(6), Validators.maxLength(16)])]
});
}
}
Here are the files as it is setup in the directory
project directory
These are the errors I seem to be getting whenever I run ionic serve. This may also be adding to the cause of the problem
enter image description here
I have looked around and the solutions I have tried don't seem to work. I also seem to be getting an error on line 8 of my login file where it attempts to import '#angular/forms' which may be the cause of the problem. Help is gladly appreciated
What I am trying to do is when the splash screen is loading, a http request is made to the server to pull some information and pass the response to another page.
Below is the code I am working with.
import { Component } from '#angular/core';
import { Platform, LoadingController } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';
import { CacheService } from "ionic-cache/ionic-cache";
import { Apis } from './apis';
import { StayPage} from '../pages/stay/stay';
#Component({
templateUrl: 'app.html',
providers: [Apis]
})
export class MyApp {
rootPage = StayPage;
constructor(platform: Platform, cache: CacheService, public loadingCtrl: LoadingController, public Apis: Apis ) {
cache.setDefaultTTL(60 * 60);
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
this.Apis.types().subscribe( response => {
response.results;
StatusBar.styleDefault();
Splashscreen.hide();
}, err => {
this.Apis.error( err );
});
});
}
}
When I run the above code, the splash screen is stuck on loading and doesn't move to another page.
You need to make HTTP request in constructor or ngOnInit of StayPage.
export class StayPage implements OnInit {
...
constructor(public navCtrl: NavController,
public navParams: NavParams
public http: Http) { }
ngOnInit(){
this.http.get(apiUrl)
.subscribe(
responseSuccess => ...
responseError => ...
}
}
}