Guest User

Untitled

a guest
Apr 6th, 2018
293
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 7.56 KB | None | 0 0
  1. import { Injectable, Inject, Component, OnInit, AfterViewInit, NgZone, ElementRef, NgModule, ViewChild } from '@angular/core';
  2. import { FormBuilder, FormGroup, FormControl, Validators } from '@angular/forms';
  3. import { Http, HttpModule, Response, Headers, RequestOptions } from '@angular/http';
  4. import { trigger, state, animate, keyframes, transition, style } from '@angular/animations';
  5. import { Router, ActivatedRoute } from '@angular/router';
  6. import { MatAutocompleteSelectedEvent } from '@angular/material';
  7.  
  8. import { AgmCoreModule, MapsAPILoader } from '@agm/core';
  9. import { } from '@types/googlemaps';
  10.  
  11. import { SearchService } from '../../../services/search.service';
  12. import { ISearchTrade } from '../../../models/search.trade.interface';
  13. import { ICategory } from '../../../models/category.interface';
  14.  
  15. import { TranslationEmitterService } from '../../../services/translation.emitter.service';
  16.  
  17. import { fadeInAnimation } from '../../../animations/fadeIn.animation';
  18. import { slideInFadeInAnimation } from '../../../animations/slideInFadeIn.animation';
  19.  
  20. import { Subscription } from 'rxjs/Rx';
  21. import { Observable } from 'rxjs/Observable';
  22. import { startWith } from 'rxjs/operators/startWith';
  23. import { map } from 'rxjs/operators/map';
  24.  
  25. import 'rxjs/add/operator/catch';
  26.  
  27. @Component({
  28. selector: 'searchTrade',
  29. templateUrl: './searchTrade.component.html',
  30. styleUrls: ['./searchTrade.component.css'],
  31. animations: [
  32. trigger(
  33. 'moveLabel', [
  34. state('moveUp', style({
  35. opacity: 0.75,
  36. top: '4px',
  37. fontSize: '14px'
  38. })),
  39. state('moveDown', style({
  40. opacity: 1.0,
  41. top: '20px',
  42. fontSize: '14px'
  43.  
  44. })),
  45. transition('* => moveUp', animate('400ms ease-in-out')),
  46. transition('* => moveDown', animate('400ms ease-in-out'))
  47. ]),
  48. fadeInAnimation,
  49. slideInFadeInAnimation
  50. ],
  51. providers: [SearchService]
  52. })
  53. export class SearchTradeComponent {
  54.  
  55. filteredOptions: Observable<ICategory[]>;
  56. options: ICategory[];
  57.  
  58. categorySubscription: Subscription;
  59. translationSubscription: Subscription;
  60.  
  61. private details: ISearchTrade = { trade: '', location: '' };
  62. searchForm: FormGroup;
  63.  
  64. toHighlight: string = '';
  65.  
  66. errors: string = '';
  67. isRequesting: boolean = false;
  68. submitted: boolean = false;
  69.  
  70. state: string = 'moveDown';
  71.  
  72. tradeState: string = 'moveDown';
  73. locationState: string = 'moveDown';
  74.  
  75. formState: string = 'active'; //can ba active, submitting, complete, error
  76.  
  77. public latitude: number;
  78. public longitude: number;
  79. public trade: number;
  80.  
  81. @ViewChild("search")
  82. public searchElementRef: ElementRef;
  83.  
  84. googlePlacesOptions = {
  85. types: [],
  86. componentRestrictions: { country: 'PT' }
  87. };
  88.  
  89. constructor(
  90. fb: FormBuilder,
  91. private router: Router,
  92. private service: SearchService,
  93. private translationService: TranslationEmitterService,
  94. private http: Http,
  95. private mapsAPILoader: MapsAPILoader,
  96. private ngZone: NgZone) {
  97.  
  98. this.searchForm = fb.group({
  99. 'tradeCtrl': ['', Validators.compose([Validators.required, Validators.minLength(3), Validators.pattern('[^0-9]*')])],
  100. 'locationCtrl': ['', Validators.compose([Validators.required])]
  101. });
  102.  
  103. }
  104.  
  105. ngOnInit() {
  106.  
  107. this.categorySubscription = this.service.getCategories().subscribe((categories: ICategory[]) => {
  108.  
  109. this.options = categories;
  110.  
  111. this.filteredOptions = this.searchForm.get('tradeCtrl').valueChanges
  112. .pipe(
  113. startWith(''),
  114. map(options => options ? this.filter(options) : this.options.slice())
  115. );
  116. });
  117.  
  118.  
  119. //load Places Autocomplete
  120. this.mapsAPILoader.load().then(() => {
  121. let autocomplete = new google.maps.places.Autocomplete(this.searchElementRef.nativeElement, {
  122. types: ["address"]
  123. });
  124. autocomplete.addListener("place_changed", () => {
  125. this.ngZone.run(() => {
  126. //get the place result
  127. let place: google.maps.places.PlaceResult = autocomplete.getPlace();
  128.  
  129. //verify result
  130. if (place.geometry === undefined || place.geometry === null) {
  131. return;
  132. }
  133.  
  134. //set latitude, longitude
  135. this.latitude = place.geometry.location.lat();
  136. this.longitude = place.geometry.location.lng();
  137. });
  138. });
  139. });
  140.  
  141.  
  142. this.translationSubscription = this.translationService.languageChange$.subscribe(
  143.  
  144. lang => this.refreshAutoCompleteItems(lang)
  145. // x => console.log("translate subscription " + x)
  146. );
  147. }
  148.  
  149. ngOnDestroy() {
  150. this.categorySubscription.unsubscribe();
  151. this.translationSubscription.unsubscribe();
  152. }
  153.  
  154. refreshAutoCompleteItems(lang: string) {
  155. console.log("in subscription " + lang);
  156. }
  157.  
  158. filter(val: string): ICategory[] {
  159. this.toHighlight = val;
  160.  
  161. return this.options.filter(x =>
  162. x.name.toUpperCase().indexOf(val.toUpperCase()) !== -1
  163. );
  164. }
  165.  
  166.  
  167. onTradeSelected(event: any, selected: ICategory) {
  168. if (event.isUserInput) {
  169. this.trade = selected.id;
  170. }
  171. }
  172.  
  173. inputFocusIn(event: any) {
  174. console.log("in input focus");
  175.  
  176. switch (event.target.id) {
  177. case 'tradeCtrl':
  178. this.tradeState = 'moveUp';
  179. break;
  180. case 'locationCtrl':
  181. this.locationState = 'moveUp';
  182. break;
  183. }
  184. }
  185.  
  186. inputFocusOut(event: any) {
  187.  
  188. if (this.searchForm.get(event.target.id)!.value == null ||
  189. this.searchForm.get(event.target.id)!.value != "")
  190. return;
  191.  
  192. switch (event.target.id) {
  193. case 'tradeCtrl':
  194. this.tradeState = 'moveDown';
  195. break;
  196. case 'locationCtrl':
  197. this.locationState = 'moveDown';
  198. break;
  199. }
  200. }
  201.  
  202. submit(form: any): void {
  203. console.log("in the form submit");
  204. console.log(form);
  205.  
  206. this.submitted = true;
  207. this.isRequesting = true;
  208. this.errors = '';
  209.  
  210. if (this.searchForm.valid) {
  211.  
  212. let headers = new Headers({ 'Content-Type': 'application/json' });
  213. let options = new RequestOptions({ headers: headers });
  214. this.details.trade = form['tradeCtrl'];
  215. this.details.location = form['locationCtrl'];
  216.  
  217. this.formState = 'submitting';
  218.  
  219. this.service.find(this.details.trade, this.details.location)
  220. .finally(() => this.isRequesting = false)
  221. .subscribe(
  222. result => {
  223. if (result) {
  224. this.router.navigate(['/dashboard/home']);
  225. }
  226. },
  227. error => this.errors = error);
  228.  
  229. }
  230. else {
  231.  
  232. Object.keys(this.searchForm.controls).forEach(key => {
  233. this.searchForm.controls[key].markAsTouched();
  234. this.searchForm.controls[key].markAsDirty();
  235. });
  236. }
  237.  
  238. }
  239.  
  240. }
Advertisement
Add Comment
Please, Sign In to add comment