File

src/pages/contact/contact.ts

Metadata

selector page-contact
templateUrl contact.html

Index

Properties
Methods

Constructor

constructor(quotationProvider: QuotationProvider, navCtrl: NavController, modalCtrl: ModalController, http: HttpClient, alertController: AlertController, fb: FormBuilder, geolocation: Geolocation, navParams: NavParams)

Upon construction, the form and its validation is initialized. Also gets geolocation data

Parameters :
Name Type Optional Description
quotationProvider QuotationProvider No
navCtrl NavController No

Controls navigation

modalCtrl ModalController No

Controls the modal that is presented. Used for the About page modal

http HttpClient No

Provides the service to handle HTTP requests

alertController AlertController No

Allows for alerts to appear

fb FormBuilder No

Provides the service to build a form

geolocation Geolocation No

Ionic Cordova plugin to natively handle geolocation data

navParams NavParams No

Methods

addQuoteToMessage
addQuoteToMessage()
Returns : void
alertSing
alertSing()
Returns : void
getGeolocation
getGeolocation()

Uses the Ionic geolocation module to obtain the current longitude and lattitude

Returns : void
getGoogleAddress
getGoogleAddress(lat: , lng: )

Makes an API call to Google Maps to get the address from the geolocation data

Parameters :
Name Optional Description
lat No

Current latitude value

lng No

Current longitude value

Returns : any

A JSON array with various details of the address as returned by the Google Maps API

onSubmit
onSubmit()

Called upon valid form submission. Obtains values to submit from form, then retrieves geolocation data if specified, and finally posts the data to the email server.

Returns : void
openModal
openModal()

Opens the About modal

Returns : void
postMessage
postMessage(name: , email: , message: , address: )

Completes the HTTP POST request to the email server with the specified data

Parameters :
Name Optional Description
name No

Name value from form

email No

Email value from form

message No

Message value from form

address No

Address value as determined by getGoogleAddress(), if specified

Returns : void
presentAlert
presentAlert()

Alert component that is called upon form submission

Returns : void
shouldLocationBeSent
shouldLocationBeSent()

Evaluates to true if the Send Location checkbox is checked in the form

Returns : boolean

Properties

Public addQuoteDisplay
addQuoteDisplay:
Default value : new Observable((data) => { setInterval(() => { data.next(this.quotationProvider.isQuoteStarted()); }, 1000); })
Public alertController
alertController: AlertController
Type : AlertController
Allows for alerts to appear
amount
amount: string
Type : string
email
email:
Default value : new FormControl('', [Validators.required, Validators.email] )

FormControl used to validate email input

Public modalCtrl
modalCtrl: ModalController
Type : ModalController
Controls the modal that is presented. Used for the About page modal
myGroup
myGroup:
Default value : new FormGroup({ name: new FormControl(), email: new FormControl(), message: new FormControl() })

FormGroup used as a model for form input

Public navCtrl
navCtrl: NavController
Type : NavController
Controls navigation
Public navParams
navParams: NavParams
Type : NavParams
positionLat
positionLat: number
Type : number
Default value : 0

Latitude value obtained by the Geolocation module

positionLong
positionLong: number
Type : number
Default value : 0

Longitude value obtained by the Geolocation module

Public quotationProvider
quotationProvider: QuotationProvider
Type : QuotationProvider
Public quoteMessage
quoteMessage: string
Type : string
Default value : ''
resName
resName: string
Type : string
sendLocation
sendLocation:
Default value : true

Determines whether the user's geolocation should be sent with the user query

submitted
submitted:
Default value : false

Evaluates to true when a server response is received.

import { Geolocation } from '@ionic-native/geolocation';
import { Component } from '@angular/core';
import { NavController, AlertController } from 'ionic-angular';
import { HttpClient } from '@angular/common/http';
import { FormControl, Validators, FormGroup, FormBuilder } from '@angular/forms';
import { ModalController } from 'ionic-angular';
import { AboutPage } from '../about/about';
import { IonicPage, NavParams } from 'ionic-angular';
import { QuotationProvider } from './../../providers/quotation/quotation';
import { Observable } from 'rxjs';
/*
  Generated class for the ModelLoaderProvider provider.

  See https://angular.io/guide/dependency-injection for more info on providers
  and Angular DI.
*/

@Component({
  selector: 'page-contact',
  templateUrl: 'contact.html'
})
export class ContactPage {
  amount : string;
  resName : string;
  /**
   * Evaluates to true when a server response is received.
   */
  submitted = false;

  /**
   * FormControl used to validate email input
   */
  email = new FormControl('', [Validators.required, Validators.email] );

  /**
   * Determines whether the user's geolocation should be sent with the user query
   */
  sendLocation = true;

  /**
   * Latitude value obtained by the Geolocation module
   */
  positionLat = 0;
  
  /**
   * Longitude value obtained by the Geolocation module
   */
  positionLong = 0;

  public quoteMessage = '';
  /**
   * FormGroup used as a model for form input
   */
  myGroup = new FormGroup({
    name: new FormControl(),
    email: new FormControl(),
    message: new FormControl()
  });

  /**
   * Upon construction, the form and its validation is initialized. Also gets geolocation data
   * @param navCtrl Controls navigation
   * @param modalCtrl Controls the modal that is presented. Used for the About page modal
   * @param http Provides the service to handle HTTP requests
   * @param alertController Allows for alerts to appear 
   * @param fb Provides the service to build a form
   * @param geolocation Ionic Cordova plugin to natively handle geolocation data
   */
  constructor(public quotationProvider: QuotationProvider ,public navCtrl: NavController, public modalCtrl : ModalController, private http: HttpClient, 
    public alertController: AlertController, private fb: FormBuilder, private geolocation: Geolocation, public navParams: NavParams) {
      
     // this.amount = navParams.get('data');
      //this.resName = navParams.get('resName');
      //this.quotationProvider.attempt();
    this.myGroup = this.fb.group({  
      'name': ['', Validators.compose([Validators.required, Validators.minLength(1)])],
      'email': ['', Validators.compose([Validators.maxLength(70), Validators.pattern('^[_A-Za-z0-9-\\+]+(\\.[_A-Za-z0-9-]+)*@[A-Za-z0-9-]+(\\.[A-Za-z0-9]+)*(\\.[A-Za-z]{2,})$'), Validators.required])],
      'message': ['', Validators.compose([Validators.required, Validators.minLength(1)])]
    });

    this.getGeolocation();
  }

  /**
	 * Opens the About modal
	 */
  openModal() {
    var data = { message : 'hello world' };
    var homePage = this.modalCtrl.create(AboutPage,data);
    homePage.present();
    
  }
    
  /**
   * Called upon valid form submission. Obtains values to submit from form, then retrieves geolocation data if specified,
   * and finally posts the data to the email server.
   */
  onSubmit() {
    const contactName = this.myGroup.get('name').value;
    const contactEmail = this.myGroup.get('email').value;
    const contactMessage = this.myGroup.get('message').value;
    this.presentAlert();
    this.myGroup.reset();

    if (this.shouldLocationBeSent() == true) {
      this.getGeolocation();
      let googleAddress: any;
      this.getGoogleAddress(this.positionLat, this.positionLong)
        .then(data => {
          googleAddress = data.results[0].address_components[3].long_name + ', ' + 
            data.results[0].address_components[4].long_name + ', ' + data.results[0].address_components[5].long_name;
           this.postMessage(contactName, contactEmail, contactMessage, googleAddress);
        })
        .catch(error => console.error(error));    
    } else {
      this.postMessage(contactName, contactEmail, contactMessage, 'Undisclosed location');
    }
  }

  /**
   * Alert component that is called upon form submission
   */
  presentAlert() {
    let alert = this.alertController.create({
      title: 'Message sent!',
      subTitle: 'Your message has been sent. A member of our team will get back to you as soon as possible.',
      buttons: ['Dismiss']
    });
  
    alert.present();
  }

  /**
   * Completes the HTTP POST request to the email server with the specified data
   * @param name Name value from form
   * @param email Email value from form
   * @param message Message value from form
   * @param address Address value as determined by getGoogleAddress(), if specified
   */
  postMessage(name, email, message, address) {
    console.log('Name: ' + name + ' Email: ' + email + ' Msg: ' + message + ' Address: ' + address);
    let messageToSend = message + '\nSent from:  ' + address;
    this.http.post('https://us-central1-testproject-ee885.cloudfunctions.net/app/sendmail',
    {'subject': name, 'text': messageToSend, 'email': email}
      ).subscribe(data1 => {
        console.log(data1);
        if (data1 == 'sent') {
          this.submitted = true;
        }
      });
  }

  /**
   * Evaluates to true if the Send Location checkbox is checked in the form
   */
  shouldLocationBeSent() {
    return this.sendLocation;
  }

  /**
   * Uses the Ionic geolocation module to obtain the current longitude and lattitude
   */
  getGeolocation() {
    this.geolocation.getCurrentPosition().then((response) => {
      this.positionLat = response.coords.latitude;
      this.positionLong = response.coords.longitude;
    }).catch((error) => {
      console.error("Error getting geolocation data: " + error);
    });
  }

  /**
   * Makes an API call to Google Maps to get the address from the geolocation data
   * @param lat Current latitude value
   * @param lng Current longitude value
   * @returns A JSON array with various details of the address as returned by the Google Maps API
   */
  getGoogleAddress(lat, lng) {
    const latlng = lat + ',' + lng;
    return fetch('https://maps.googleapis.com/maps/api/geocode/json?latlng=' + latlng + '&key=AIzaSyD1GI0J6QPOYxqxBMG4Z2oIr-ctibYoRiI')
      .then(
        response => {
          return response.json();
        });
  }
  addQuoteToMessage() {
    const quoteList = this.quotationProvider.getQuoteList();
    this.quoteMessage = '\nI\'d like to receive a quote for the following items:\n';
    this.quoteMessage += '=================\n';
    quoteList.forEach((element, index) => {
      this.quoteMessage += (index + 1) + '. ' + element.name + ' x' + element.amount + '\n';
    });
    this.quoteMessage += '=================\n';

    const messageText = this.myGroup.get('message').value;
    this.myGroup.patchValue({
      message: messageText + this.quoteMessage
    });
  }

  public addQuoteDisplay = new Observable((data) => {
    setInterval(() => {
      data.next(this.quotationProvider.isQuoteStarted());
    }, 1000);
  });

  alertSing()
  {
    let alert = this.alertController.create({
      title: 'Hey There!',
      message:`
      Got a query about one of Brahope's products? Want to request a quote? Send Bramhope a message!`,
      buttons: ['OK']
    });
    alert.present();
  }

}
<!-- /**
 * File Name:       contact.html
 * Version Number:  v1.1
 * Author:          Orisha Orrie, Tobias Bester
 * Project Name:    Ninshiki
 * Organization:    Software Sharks
 * User Manual:     Refer to https://github.com/OrishaOrrie/SoftwareSharks/blob/master/Documentation/User%20Manual.pdf
 * Update History:
 * ------------------------------------------
 * Date         Author		Description
 * 20/07/2018   Orisha		Created component
 * 15/08/2018   Orisha    Added backend functionality
 * 18/09/2018   Orisha    Fixed layout
 * ------------------------------------------
 * Functional Description:
 *  This page includes ways to contact the Bramhope group in order to request a quote or report any issues.
 */ -->

<ion-header>
    <ion-navbar>
        <ion-title>Contact Us</ion-title>
        <ion-buttons end>
            <button ion-button icon-only (click) ="alertSing()"  >
             <ion-icon name="information-circle" style="color: white"></ion-icon>
           </button>
          </ion-buttons>
        <ion-buttons end>
            <button ion-button icon-only (click) ="openModal()"  >
             <ion-icon name="help-circle" style="color: white"></ion-icon>
           </button>
          </ion-buttons>
      </ion-navbar>
</ion-header>
<!-- form to submit email to Bramhope group -->
<ion-content padding id ="formcol">
<h1 style="color: black;">Issues? Quote? Contact us!</h1>
    <form [formGroup]="myGroup"  *ngIf="!submitted" >
 
      <ion-item class="inputs">
        <ion-label class = 'bob' color="secondary" stacked>Full Name</ion-label>
        <ion-input id="name" type="text" required formControlName="name"></ion-input>
      </ion-item>
      <ion-item class="inputs">
        <ion-label class = 'bob' color="secondary" stacked>Email Address</ion-label>
        <ion-input id="email" type="email" required formControlName="email" ></ion-input>
      </ion-item>
      <ion-item class="inputs">
        <ion-label class = 'bob' color="secondary" stacked>Message</ion-label>
        <ion-textarea rows="8" maxLength="500" id="message" type="text" required formControlName="message" style = " height: 140px"></ion-textarea >
      </ion-item>
    </form>
      <ion-item class="inputs">
        <ion-label style="font-weight: bold" color="secondary">Send location data</ion-label>
        <ion-checkbox color="secondary" checked="true" [(ngModel)]="sendLocation"></ion-checkbox>
      </ion-item>
      <button *ngIf="addQuoteDisplay | async" ion-button full round color= "tertiary" (click)="addQuoteToMessage()" >Add Quote</button>
    <button ion-button full round color= "tertiary" [disabled]="!myGroup.valid" (click)="onSubmit()">Send</button>
   
    
</ion-content>
Legend
Html element
Component
Html element with directive

result-matching ""

    No results matching ""