Passing an array between pages in ionic 2 - angularjs

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

Related

Angular/Typescript - Add timestamp in array services

I'm trying to add a timestamp OnInnit in order to record the time a user accessed a page. I would like to add the timestamp in an array found in my services, but I'm really struggling to find my way around this, and keep getting errors. Any help would really be appreciated.
tracker-data.ts
export class TrackerData {
entry?: number;
exit?: number;
clicks?: number;
url?: string;
}
tracker.service.ts
import { Injectable } from '#angular/core';
import { TrackerData } from '../modules/tracker-data';
#Injectable({
providedIn: 'root'
})
export class TrackerService {
trackerData: TrackerData;
websiteData: TrackerData[];
public entryTime: {entry: number} [] = [];
constructor() { }
}
tracker.component.ts
import { Component, OnInit, OnDestroy } from '#angular/core';
import { TrackerService } from '../services/tracker.service';
import { TrackerData } from '../modules/tracker-data';
#Component({
selector: 'app-tracker',
templateUrl: './tracker.component.html',
styleUrls: ['./tracker.component.scss']
})
export class TrackerComponent implements OnInit, OnDestroy {
constructor(
public trackerService: TrackerService,
private websiteData: TrackerData[]
) { }
ngOnInit(): void {
const timeOfEntry = Date.now();
this.websiteData.push(timeOfEntry); // Type 'number' has no properties in common with type 'TrackerData'.
}
I know the above code might not make sense, but I'm fairly new to this and I'm really trying.
The error is pretty clear, you are trying to add a date (the timestamp) as an instance of TrackerData, which is clearly not. In this case you need to create an instance of the TrackerData and then assign the timestamp value.
const trackerData = new TrackerData(); // create the instance
trackerData.entry = Date.now(); // assign the the entry timestamp
this.websiteData.push(trackerData); // add to array
export class TrackerData {
entry?: number;
exit?: number;
clicks?: number = 0;
url?: string;
}
import { Injectable } from '#angular/core';
import { TrackerData } from '../modules/tracker-data';
#Injectable({
providedIn: 'root'
})
export class TrackerService {
websiteData: TrackerData[];
constructor() { }
addTrackerData(trackerData: TrackerData): void {
this.websiteData.push(trackerData);
//log data on the server if you want
}
}
import { Component, OnInit, OnDestroy } from '#angular/core';
import { TrackerService } from '../services/tracker.service';
import { TrackerData } from '../modules/tracker-data';
import { Router } from '#angular/router';
#Component({
selector: 'app-tracker',
templateUrl: './tracker.component.html',
styleUrls: ['./tracker.component.scss']
})
export class TrackerComponent implements OnInit, OnDestroy {
private pageData: TrackerData = new TrackerData();
constructor(
private trackerService: TrackerService,
private router: Router
) { }
#HostListener('click', ['$event.target'])
onClick(btn) {
this.pageData.clicks++;
}
ngOnInit(): void {
this.pageData.entry = Date.now();
this.pageData.url= this.router.url;
}
ngOnDestroy(): void {
this.pageData.exit = Date.now();
this.trackerService.addTrackerData(this.pageData);
}
this is the simplest version of what you want!
if you want to keep data when the page gets refresh, you need to put data in the cache!

Undefined Data When Calling From JSON in Ionic 2

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 .

Can't inject service in component in Ionic 2

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.

Angular 2 Communicating with <router-outlet> components

I have a search bar in a header component.
Beneath that, I have a "router-outlet" in that same component.
The search bar (input txtfield), once enter is pressed, needs to send the search string (event.target.value) to the component that resides within the router-outlet beneath it so that it can run a method to return the results.
I have no clue what the best way is to achieve this.
UPDATED with code..
app.component.html:
<div class="white-container">
<input name="searchStr" [(ngModel)]="searchStr" (keyup.enter)="searchCourse($event)">
</div>
<router-outlet></router-outlet>
app.component.ts:
import { Component, OnInit } from '#angular/core';
import { CourseService } from './services/courses.service';
import { Course } from './Course';
#Component({
selector: 'my-app',
templateUrl: 'app.component.html',
providers: [CourseService]
})
export class AppComponent implements OnInit {
constructor(private _courseService: CourseService) {
}
searchCourse(event) {
// the user search string here...
}
}
/course-listings/course-listings.component.ts:
import { Component, OnInit } from '#angular/core';
import { CourseService } from './services/courses.service';
import { Course } from './Course';
#Component({
selector: 'app-course-listings',
templateUrl: './course-listings.component.html',
styleUrls: ['./course-listings.component.css'],
providers: [CourseService]
})
export class AppComponent implements OnInit {
course: Course[];
constructor(private _courseService: CourseService) {
}
searchCourse(evt) {
// This works once it's fired...
this._courseService.findCourse(evt)
.subscribe(courses => {
this.course = courses;
});
}
}
/services/courses.service.ts:
import {Injectable} from '#angular/core';
import {Http} from '#angular/http';
import 'rxjs/add/operator/map';
#Injectable()
export class CourseService {
constructor(private _http:Http) {
}
getCourses(search) {
return this._http.get('/api/v1/courses/'+search)
.map(res => res.json());
}
}
FIX FOUND
Günter Zöchbauer was correct. I used a service w/ subscribe and observables to do it. Thanks.
An event.subscriber would be required in the constructor to pass to router-outlet.
Similar to the answer in this Angular 2 router event listener.
So, once the click is done, the subscriber event will be executed based on on the navigationend event, then the value can be accessed.

Angular2 Component Router : Capture query parameters

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

Resources