I have a simple ionic 2 app.
Created at service
import { Storage } from '#ionic/storage';
import { Injectable } from '#angular/core';
import { Http, Headers } from '#angular/http';
import { AlertController } from 'ionic-angular';
import { NavController, NavParams } from 'ionic-angular';
import { AgendaPage } from '../pages/agenda/agenda';
import { LoginPage } from '../pages/login/login';
import 'rxjs/add/operator/map';
#Injectable()
export class Auth {
constructor(public http: Http, public storage: Storage, public alertCtrl: AlertController, public navCtrl: NavController) {}
}
app.components.ts registration
import { Component, ViewChild } from '#angular/core';
import { Nav, Platform } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';
import { Auth } from '../providers/auth';
import { Rides } from '../providers/rides';
import { AgendaPage } from '../pages/agenda/agenda';
import { LoginPage } from '../pages/login/login';
#Component({
templateUrl: 'app.html',
providers: [Auth, Rides]
})
export class MyApp {
#ViewChild(Nav) nav: Nav;
rootPage: any = LoginPage;
pages: Array<{title: string, component: any}>;
constructor(public platform: Platform) {
this.initializeApp();
// used for an example of ngFor and navigation
this.pages = [
{ title: 'Minha Agenda', component: AgendaPage }
];
}
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.
StatusBar.styleDefault();
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);
}
}
Trying to inject it into a component
import { Component } from '#angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { Auth } from '../../providers/auth';
/*
Generated class for the Agenda page.
See http://ionicframework.com/docs/v2/components/#navigation for more info on
Ionic pages and navigation.
*/
#Component({
selector: 'page-agenda',
templateUrl: 'agenda.html',
providers: [Auth]
})
export class AgendaPage {
openRides: any;
constructor(public navCtrl: NavController, public navParams: NavParams, private auth: Auth) {}
}
I get the following error:
Can't resolve all parameters for AgendaPage: (NavController,
NavParams, ?).
What I find strange is that I have a very similar other component where I can user the service without problems:
import { Component } from '#angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { Auth } from '../../providers/auth';
/*
Generated class for the Login page.
See http://ionicframework.com/docs/v2/components/#navigation for more info on
Ionic pages and navigation.
*/
#Component({
selector: 'page-login',
templateUrl: 'login.html',
providers: [Auth]
})
export class LoginPage {
email: string;
password: string;
constructor(public navCtrl: NavController, public navParams: NavParams, private auth: Auth) {}
login() {
}
}
This works perfectly.
If it's an authentication service, you probably don't need to provide it at the lower levels of abstraction. It still needs to be imported to be used, but it doesn't need to be added to the providers[] in your lower tier components.
This may be causing the error, as for some reason it might not be able to provide an instance of Auth at that level of abstraction for whatever reason. Notably, I try not to use constructors on my services -- that may be causing the issue as well (or both issues together.)
The problem here is circular dependency. You are already importing the component in your service and want to inject the service in the same component. So angular does not know which to load first.
You need to look into forwardref.
In your component constructor,
constructor(...,#Inject(forwardref(()=>Auth))auth)
You might want to refer here for more.
Related
I'm new in Ionic 2 and I'm having troubles with passing data between pages. In my Home.ts file I have a global array that contains some numbers I calculated and i want to pass it to my Table.ts file, to show it in a HTML table with the *ngFor method.
this is the Function in Home.ts where i fill the array and try to push (i will skip the calculations, becacause i know they are correct).
`import { Component } from '#angular/core';
import { AlertController } from 'ionic-angular';
import { IonicPage,NavController, NavParams} from 'ionic-angular';
import {Table} from '../table/table';
export class HomePage {
averagesList: Array <number> =[];
constructor(public alerCtrl: AlertController,
public navCtrl: NavController,
public navParams: NavParams)
{}
Calculate(){
var Averages=[];
//Calculations on the 'Averages' Array
this.averagesList = Averages;
this.navCtrl.push(Table,this.averagesList);
}
}
So I try to print it in my Table.ts file but it gives me undefined result
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import {HomePage} from '../home/home';
#IonicPage()
#Component({
selector: 'page-table',
templateUrl: 'table.html',
})
export class Table{
constructor(public navCtrl: NavController, public navParams: NavParams) {
}
ionViewDidLoad() {
console.log(this.navParams.get('averagesList'));
}
}
I've tried to pass a let variable and it worked, so why doesn't it work with arrays?
Your mistake is using console.log(this.navParams.get('averagesList'));
Here 'averagesList' is the key.
To get it this way, you need to send as :
this.navCtrl.push(Table,{'averagesList' : this.averagesList});
Else:
if you directly send as
this.navCtrl.push(Table,this.averagesList);
You can retrieve value like so:
console.log(this.navParams.data);
you can use services to do so. Just like in angular2 you can import your service within the constructor and use the property like this.
import {OnInit} from '#angular/core';
import {someService} from ./somepath;
...
export class someClass implements OnInit{
let myTmpVar; //we will capture the shared data in this variable
constructor (private smService: someService){ ... }
ngOnInit{
this.myTmpVar = this.smService.SharedServiceData;
}
...
}
It's better to use service for passing nested data. In your case calculations object.
You can create messageService and listen to changes, something like below.
import {Injectable} from '#angular/core';
import {Observable} from 'rxjs';
import {Subject} from 'rxjs/Subject';
#Injectable()
export class LocalMsgService {
private subject = new Subject();
sendMessage(message) {
this.subject.next(message);
}
clearMessage() {
this.subject.next();
}
getMessage(): Observable<any> {
return this.subject.asObservable();
}
}
Which can be used in your home.ts and table.ts pages as follows
Home.ts
//other imports comes here
import {LocalMsgService} from 'services/localMsg';
#Component({
selector: 'home-component',
templateUrl: 'home.html'
})
export class HomePage {
constructor( private msgService: LocalMsgService) {
}
dataToPass() {
console.log(this.averagesList);
this.msgService.sendMessage(this.averagesList);
}
}
Table.ts
//other imports comes here
import {LocalMsgService} from 'services/localMsg';
import {Subscription} from 'rxjs/Subscription';
#Component({
selector: 'page-table',
templateUrl: 'table.html',
})
export class TablePage{
items: any;
subscription: Subscription;
constructor(
public localMsgService : LocalMsgService) {
this.subscription = this.localMsgService.getMessage().subscribe(msg => {
this.items = msg;
});
}
}
I have a firebase URL to get some test data from as I'm still learning Ionic 2. Originally I had the error 'No HTTP Provider', but I fixed that by adding HttpModule to the app.module.ts file, but since that my data is always coming back as undefined.
The service is in it's own file (ww-api.service.ts):
import { Injectable } from '#angular/core';
import { Http, Response } from '#angular/http';
#Injectable()
export class WildWalkApi {
private baseUrl = 'https://i2test-ea07c.firebaseio.com/';
constructor(private http: Http) {}
getLoginTest(){
return new Promise(resolve => {
this.http.get(this.baseUrl + 'login.json')
.subscribe(res => resolve(res.json()));
});
}
}
Then this is exported using a shared file (shared.ts):
export * from './ww-api.service';
This then goes into app.componant.ts:
import { WildWalkApi } from './shared/shared';
#Component({
templateUrl: 'app.html',
providers: [
WildWalkApi,
HttpModule
]
})
And finally I try and use the data in my view:
import { Component } from '#angular/core';
import { IonicPage, NavController, NavParams } from 'ionic-angular';
import { WildWalkApi } from "../../app/shared/shared";
#IonicPage()
#Component({
selector: 'page-home-logged-in',
templateUrl: 'home-logged-in.html',
})
export class HomeLoggedIn {
private login;
constructor(public navCtrl: NavController, public navParams: NavParams, private wwapi: WildWalkApi) {
}
ionViewDidLoad() {
this.wwapi.getLoginTest().then(data => this.login = data);
console.log('ionViewDidLoad HomeLoggedIn ' + this.login);
}
}
However this.login is always coming back as undefined.
In your code You're trying to print the value right after sending the request but data is not available at that time .
You can use Event for it . Refer http://ionicframework.com/docs/api/util/Events/
sample is here
In that file from where you want to use that event is
this.events.publish('user:loggedIn', data);
and that file where you want to show that data is
this.events.subscribe('user:loggedIn', (data) => {
console.log("page 1 data "+data);
this.page1Message=data;
});
This may work for you .
I'm trying to load a JSON from remote server which I already obtained in a service using http.get(), but I can't get the data from my service into my page. I can see the json data is loaded in the service in console.log but can't find a way to get it into my page so I can use those data in my UI. Does anybody see what i'm doing wrong here?
here is the code of my service
import { Injectable } from '#angular/core';
import { Http } from '#angular/http';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/timeout';
#Injectable()
export class MyService {
returnedData;
constructor(public http: Http) {
console.log('Hello MyService Provider');
}
getRemoteData(){
console.log('Hello inside getRemoteData');
this.http.get('https://randomuser.me/api/?inc=gender,name,email,phone,picture,location').map(res => res.json()).subscribe(data => {
console.log(data);
this.returnedData=data;
});
return returnedData;
}
}
here is my page
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { MyService } from '../../providers/my-service';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
myJson;
constructor(public navCtrl: NavController, public serviceOne: MyService) {
}
ionViewDidload(){
console.log('Hello MyService called');
this.myJson=this.serviceOne.getRemoteData;
console.log('myJson');
}
getRandomSpan(){
return Math.floor((Math.random()*10)+1);
};
}
I want to get the value of the json I received from server into myJson variable.
so I can use those data into UI.
Can we navigate/redirect to any login url (different host and application) or must we navigate/redirect only to url's within the routes of our application?
The example from the angular site suggests only application routes are permitted:
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {
if (this.authService.isLoggedIn) { return true; }
// Store the attempted URL for redirecting
this.authService.redirectUrl = state.url;
// Navigate to the login page
this.router.navigate(['/login']);
return false;
}
Have you tried navigateByUrl()?
See https://angular.io/docs/ts/latest/api/router/index/Router-class.html for usage.
But:
Why you need an "external" URL not part of your application?
I assume best practive would be an external authService instead of an seperate "Login-Page-Application". or such.
e.g.
import { Injectable } from '#angular/core';
import {CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot, Router} from '#angular/router';
import {Observable} from "rxjs";
import {AuthService} from "../services/auth.service";
#Injectable()
export class LoginGuard implements CanActivate {
constructor(protected router: Router, protected authService: AuthService) { }
canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> | boolean {
console.log('AuthGuard#canActivate called');
if (state.url !== '/login' && !this.authService.isLoggedIn()) {
this.router.navigate(['/login'], {queryParams: {redirectTo: state.url}});
return false;
}
return true;
}
}
import {Component} from "#angular/core";
import {ActivatedRoute, Router} from "#angular/router";
#Component({
templateUrl: "app/components/login/login.html"
})
export class LoginComponent {
constructor(public route: ActivatedRoute, public router: Router) { }
loginSuccessful() {
let redirect = this.route.snapshot.queryParams['redirect'];
let redirectUrl = redirect != null ? redirect : '/dashboard/';
console.log('redirect to: ' + redirect);
this.router.navigate([redirectUrl]);
}
}
I'm struggling to capture URL query string parameters being passed to my angular2 app by a 3rd party API. The URL reads http://example.com?oauth_token=123
How can I capture the value of "oauth_token" inside a component? I'm happily using the component router for basic routing it's just the query string. I have made several attempts and my latest receiving component looks like
import { Component, OnInit } from '#angular/core';
import { ActivatedRoute } from '#angular/router';
#Component({
template: ''
})
export class TwitterAuthorisedComponent implements OnInit {
private oauth_token:string;
constructor(private route: ActivatedRoute) {}
ngOnInit() {
console.log('the oauth token is');
console.log( this.route.snapshot.params.oauth_token );
}
}
Any advice is appreciated.
** UPDATE
If I comment out all my routes the query parameters will stick however, the moment I include a route the query parameters are removed on page load. Below is a stripped down copy of my routes file with one route
import {NavigationComponent} from "./navigation/components/navigation.component";
import {TwitterAuthorisedComponent} from "./twitter/components/twitter-authorised.component";
import { provideRouter, RouterConfig } from '#angular/router';
export const routes: RouterConfig = [
{ path: '', component: TwitterAuthorisedComponent }
];
export const appRouterProviders = [
provideRouter(routes)
];
If I remove the route the query params stick. Any advice?
I you can catch the query prams using the bellow solution.
import { Router, Route, ActivatedRoute } from '#angular/router';
queryParams:string;
constructor(private router: Router, private actRoute: ActivatedRoute)
{
this.queryParams=
this.router.routerState.snapshot.root.queryParams["oauth_token"];
}
Using this you will get the value of oauth_token to queryParams. I think this seems fine for you
If you need to update the value queryParams, query parameter changes you need to add some more code. Its like below.
import { Router, Route, ActivatedRoute } from '#angular/router';
queryParams:string;
sub:any;
constructor(private router: Router, private actRoute: ActivatedRoute)
{
this.queryParams=
this.router.routerState.snapshot.root.queryParams["oauth_token"];
}
ngOnInit(){
this.sub = this.router.routerState.root.queryParams.subscribe(params => {
this.queryParams = params["oauth_token"];
});
}
Hope it will work for you.
Query parameters can be obtained through the Router service.
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
#Component({
template: ''
})
export class TwitterAuthorisedComponent implements OnInit {
private oauth_token:string;
constructor(private router: Router) {}
ngOnInit() {
console.log('the oauth token is');
console.log( this.router.routerState.snapshot.queryParams.oauth_token );
}
}
You can do this by
import { Component, OnInit } from '#angular/core';
import { Router } from '#angular/router';
#Component({
template: ''
})
export class TwitterAuthorisedComponent implements OnInit {
sub: any; //new line added
private oauth_token:string;
constructor(private router: Router) {}
ngOnInit() {
this.sub = this.route.params.subscribe(params => {
let id = +params['oauth_token'];
console.log('the oauth token is');
console.log(id);
});
}
}
Hope this will help. Thank you