Http object making request on URL that is different unitialized controller


#1

I have a login and signup component page. I also have a tabs page after you login with a post url to pull event data from my api using angular Http post. When I go into signup and make my post request it is calling the url in the tabs component, which has not been initialized or opened yet, when it should be calling my “joinUrl” in signup It is imported in login but it hasn’t been opened yet and it seems like its variables are still accessible. Does anybody have an idea of why this would happen?

Here is the code from my tabs page:

import { Component } from '@angular/core';
import { NavController, NavParams, AlertController, App} from 'ionic-angular';
import {NativeStorage} from "ionic-native";
import {Events} from "../events/events";
import {Headers, Http} from "@angular/http";
import {Home} from "../home/home";
import {LocalNotifications, Vibration} from "ionic-native";
import { Push } from 'ionic-native';

/*
  Generated class for the Tabs page.

  See http://ionicframework.com/docs/v2/components/#navigation for more info on
  Ionic pages and navigation.
*/
@Component({
  selector: 'page-tabs',
  templateUrl: 'tabs.html'
})
export class Tabs {

  public ionicHttpUrl = "https://api.ionic.io/";
  public tab1Root: any;
  public tab2Root: any;
  // private tab3Root: any;
  public username;
  public pullUserInfoUrl = "http://phplaravel-19273-43928-143690.cloudwaysapps.com/admin/get/userProfile";
  public user;
  public getEventsUrl = "http://phplaravel-19273-43928-143690.cloudwaysapps.com/admin/get/events/all";
  public events;
  public push;


  constructor(private navParams: NavParams, private http: Http, private alertCtrl: AlertController,
    public navCtrl: NavController, private app: App) {

    // this tells the tabs component which Pages
    // should be each tab's root Page
    this.tab1Root = Home;
    this.tab2Root = Events;
    // this.tab3Root = ContactPage;

    this.username = this.navParams.get('username');
    console.log(this.username);
    this.pullUserInfo();
    this.getEvents();

    this.push = Push.init({
      android: {
        senderID: '115680124833'
      },
      ios: {
        alert: 'true',
        badge: true,
        sound: 'false'
      },
      windows: {}
    });
    // this.push.rx.notification()
    //     .subscribe((msg) => {
    //         alert(msg.title + ': ' + msg.text);
    //     });

    // this.sendNote();


    NativeStorage.getItem('events').then((value) => {
      //console.log(value);
      var valueObj = JSON.parse(value);
      this.events = valueObj.events;

      var events = this.events;
      console.log(events);

      //LocalNotifications.clearAll();

      for (var i = 0; i < events.length; i++) {
        var event = events[i];
        var splitYearObj = event.date.split("/");
        var eventYear = splitYearObj[2];

        /* schedule notifications for events 
        //TODO set exact time for when the notification should go off
        figure out when events are getting scheduled/rescheduled so if app is off it still works
        Auto event refreshing so notifications are accurate; do this periodically while app is open
        */

        //need format mm/dd/yyyy
        var dateString = event.date;
        var dateSplit = dateString.split("/");
        var month = dateSplit[0] - 1;//javascript date object starts month index at 0
        var day = dateSplit[1];
        var year = dateSplit[2];

        //convert to 24 hour clock time; need hh:mm aa time format
        var timeArray = event.time_range.split('-');
        var time = timeArray[0];
        var hours = Number(time.match(/^(\d+)/)[1]);
        var timeSplit = time.split(" ");
        var AMPM = timeSplit[1];
        if (AMPM.toLowerCase().indexOf("pm") && hours < 12) hours = hours + 12;
        if (AMPM.toLowerCase().indexOf("am") && hours == 12) hours = hours - 12;

        var finalDateString = new Date(year, month, day, hours, 0, 0);//last 2 params are min and sec
        console.log("Notification date for " + event.title + " : " + finalDateString);
        var dayInMillis = 1000 * 60 * 60 * 24;

        // LocalNotifications.schedule({
        //     id: i,
        //     at: finalDateString.getTime() - dayInMillis,//schedule notification 1 day before event
        //     title: 'SWE Meeting Alert',
        //     text: event.title + " in the " + event.location + "tomorrow at " + event.time_range,
        //     ongoing: false, //sticky notification
        //     //sound: isAndroid ? 'file://sound.mp3' : 'file://beep.caf',
        //     //data: { secret: key }

        // });

        // //handle when notification fires
        // LocalNotifications.on('trigger', function () {
        //     Vibration.vibrate(1000);
        // });


      }

    });
  }



  ionViewDidLoad() {


  }



  getEvents() {
    var headers = new Headers();
    headers.append('Content-Type', 'application/json');

    this.http.get(this.getEventsUrl,
      { headers: headers })
      .map(res => res.json())
      .subscribe(data => {
        console.log(data);
        /* create local storage data of events */
        NativeStorage.setItem('events', JSON.stringify({
          events: data
        })).then(data => { 
          alert('Pulled Events. ' + data)
          console.log("success") },
          error => { alert("Storage Error" + error) }
          );
      }, error => {
        alert('Error' + error);
        console.log("Server Error  " + error);
      });
  }

  sendNote() {
    var headers = new Headers();
    headers.append('Content-Type', 'application/json');

    this.http.post(this.ionicHttpUrl + "/push/notifications",
      JSON.stringify({
        tokens: "send_to_all",
        profile: "	sweapp",
        notification: {
          "message": "Hello World!"
        }
      }), { headers: headers })
      .map(res => res.text())
      .subscribe(data => console.log(data)
      , err => console.log(err));
  }

  /**
   * Returns user profile info from db given a username
   */
  pullUserInfo() {
    var headers = new Headers();
    headers.append('Content-Type', 'application/json');

    this.http.post(this.pullUserInfoUrl,
      JSON.stringify({
        username: this.username
      }), { headers: headers })
      .map(res => res.json())
      .subscribe(data => {
        NativeStorage.setItem('user', JSON.stringify({
          username: data.username,
          id: data.id
        }));
      }
      , err => {
        this.showAlert('Server Error', "Our server is currently having difficulties. Please try again later!");
      });
  };


  showAlert(custTitle, custSubtitle) {
    let alert = this.alertCtrl.create({
      title: custTitle,
      subTitle: custSubtitle,
      buttons: ['OK']
    });
    alert.present();
  }

}

And here is my signup page code:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import {Http, Response, Headers} from '@angular/http';
import 'rxjs/Rx'; //for observable and mapping for http requests
import {Login} from "../login/login";
/*
  Generated class for the Signup page.

  See http://ionicframework.com/docs/v2/components/#navigation for more info on
  Ionic pages and navigation.
*/
@Component({
    selector: 'page-signup',
    templateUrl: 'signup.html'
})
export class Signup {

    private joinUrl = "http://phplaravel-19273-43928-143690.cloudwaysapps.com/admin/storeUser";
    public username;
    public firstName;
    public lastName;
    public major;
    public graduationYear;
    public phone;
    public majors = [
        'Aeronautical and Astronautical Engineering',
        'Architecture',
        'Aviation',
        'Biomedical Engineering',
        'Chemical Engineering',
        'Civil Engineering',
        'Computer Science and Engineering',
        'Electrical and Computer Engineering',
        'Engineering Physics',
        'Environmental Engineering',
        'Faculty/staff',
        'Food, Agricultural and Biological Engineering',
        'Industrial and Systems Engineering',
        'Materials Science and Engineering',
        'Mechanical Engineering',
        'Non-Engineering',
        'Undecided Engineering',
        'Welding Engineering'
    ];


    constructor(public navCtrl: NavController, private http: Http) { }

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

    join() {

        var headers = new Headers();
        headers.append('Content-Type', 'application/json');

        this.http.post(this.joinUrl,
            JSON.stringify({
                username: this.username, firstName: this.firstName, lastName: this.lastName,
                major: this.major, graduationYear: this.graduationYear, phone: this.phone
            }), { headers: headers })
            .subscribe(signupResult => {
                console.log("Success " + signupResult);
                alert('Success' + signupResult);

                this.navCtrl.pop();
            }, error => {
                console.log("Error  " + error);
                alert('Error' + error);
            });

    }

}