Using Object.entries(params).map to get companies from database

时间:2019-03-19 15:06:10

标签: angular

Bear with me, I have no experience with Angular and was forced to fix the search for this startup's website since my co-worker quit suddenly.

Below is the company.service.ts

import { Injectable } from '@angular/core';
import { HttpClient } from '@angular/common/http';
import { ActivatedRouteSnapshot, Resolve, RouterStateSnapshot } from '@angular/router';
import { Observable, BehaviorSubject } from 'rxjs';
import { ServerService } from '../../../_services/server.service';
@Injectable()
export class CompanyDashboardService implements Resolve<any>{
   
    query: string = "";

    /**
     * Constructor
     *
     * @param {HttpClient} http
     */
    constructor(
        private http: HttpClient,
        private server: ServerService,
    )
    {
    }
    
    serverURL = this.server.serverURL;

    /**
     * Resolver
     *
     * @param {ActivatedRouteSnapshot} route
     * @param {RouterStateSnapshot} state
     * @returns {Observable<any> | Promise<any> | any}
     */
    resolve(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<any> | Promise<any> | any
    {
        return new Promise((resolve, reject) => {

            Promise.all([
                
            ]).then(
                () => {
                    resolve();
                },
                reject
            );
        });
    }

	searchCompany(params):  Observable<any> {
        let urlParameters = Object.entries(params).map(e => e.join('=')).join('&');
        console.log(urlParameters);
        return new BehaviorSubject(this.http.get(this.serverURL + 'api/company?' + urlParameters)).asObservable();
    }
}

The search gets query parameters from the URL which is then used in

searchCompany(params): Observable {

From my understanding, the above code just retrieves all companies in the database. If I remove

(e => e.join('=')).join('&'),

The pagination breaks...

Below is the company.component.ts

import { Component, OnInit, ViewEncapsulation } from '@angular/core';
import { fuseAnimations } from '@fuse/animations';
import { CompanyDashboardService } from 'app/main/apps/company/company.service';
import { Observable, Subject } from "rxjs";
import { Router, ActivatedRoute } from '@angular/router';

@Component({
    selector     : 'company',
    templateUrl  : './company.component.html',
    styleUrls    : ['./company.component.scss'],
    encapsulation: ViewEncapsulation.None,
    animations   : fuseAnimations
})

export class CompanyDashboardComponent implements OnInit
{
	$result: Observable<any>;

	$companies: any;
	$pages: number;
	$current: number;
	$pageRange: any;

	$companiesAll: any;
	$countryList: string[];
	$stateList: string[];
	$cityList: string[];
	$industryList: string[];
	$tagList: string[];
	$reasonList: string[];
	$founderList: string[];
	$investorList: string[];
	$employeeList: string[];
	$fundingList: string[];
	$roundList: string[];
	
	$locationList: any;
	$stateListOriginal: string[];
	$cityListOriginal: string[];
	
    queries: any;

    // Private
    private _unsubscribeAll: Subject<any>;

    /**
     * Constructor
     *
     * @param {CompanyDashboardService} companyDashboardService
     * @param {ActivatedRoute} route
     */
    constructor(
        private companyDashboardService: CompanyDashboardService,
        private route: ActivatedRoute,
        private router: Router
    )
    {
        this._unsubscribeAll = new Subject();
    }

    isHovering = false;
    hoverIndex = [];
    
    // -----------------------------------------------------------------------------------------------------
    // @ Lifecycle hooks
    // -----------------------------------------------------------------------------------------------------

    /**
     * On init
     */
    ngOnInit(): void
    {
        this.route.queryParams.subscribe(params => {
            // console.log(params);
            this.queries = params;
            this.companyDashboardService.searchCompany(this.queries).subscribe(
                res => {
					this.$result = res;
					
					this.$result.forEach( companies => {

						this.$companies = companies.companies;
						this.$pages = companies.pages;
						this.$pageRange =  Array(companies.pages);
						this.$current = companies.current;
						var countryList = [];
						var stateList = [];
						this.$stateList = [];
						this.$cityList = [];
						
						if (this.queries.country === undefined) {
							if (this.queries.state === undefined) {
								this.$stateList = this.$stateListOriginal;
								this.$cityList = this.$cityListOriginal;
							} else {
								this.$stateList = this.$stateListOriginal;
								stateList = this.queries.state;
								
								for (var i in this.$locationList) {
									var location = this.$locationList[i];
									var country = location.country;
									var state = location.state;
									var city = location.city;
									
									if (stateList.includes(state)) {
										if (!this.$cityList.includes(city)) {
											this.$cityList.push(city);
										}
									}
								}
								this.$cityList.sort();
							}
						} else {
							countryList = this.queries.country;
							
							if (this.queries.state === undefined) {
								for (var i in this.$locationList) {
									var location = this.$locationList[i];
									var country = location.country;
									var state = location.state;
									var city = location.city;
									
									if (countryList.includes(country)) {
										if (!this.$stateList.includes(state)) {
											this.$stateList.push(state);
										}
										if (!this.$cityList.includes(city)) {
											this.$cityList.push(city);
										}
									}
								}
								
								this.$stateList.sort();
								this.$cityList.sort();
							} else {
								stateList = this.queries.state;
								
								for (var i in this.$locationList) {
									var location = this.$locationList[i];
									var country = location.country;
									var state = location.state;
									var city = location.city;
									
									if (countryList.includes(country)) {
										if (!this.$stateList.includes(state)) {
											this.$stateList.push(state);
										}
									}
									if (stateList.includes(state)) {
										if (!this.$cityList.includes(city)) {
											this.$cityList.push(city);
										}
									}
								}
								
								this.$stateList.sort();
								this.$cityList.sort();
							}	
					}
					});

                },
                error => {
                    console.log(error.error);
                }
            );
        })
    }
    /**
     * On destroy
     */
    ngOnDestroy(): void
    {
        // Unsubscribe from all subscriptions
        this._unsubscribeAll.next();
        this._unsubscribeAll.complete();
    }


    // -----------------------------------------------------------------------------------------------------
    // @ Private methods
    // -----------------------------------------------------------------------------------------------------
    
    mouseOver(index) {
		this.hoverIndex[index] = true;
	}

	mouseLeft(index) {
		this.hoverIndex[index] = false;
    }
    
	changePage(page): void {
		console.log(page);
		this.router.navigate(['/company'], { queryParams: {pageNo: page} });
	}
}

The code works in displaying all the companies from the database using

*ngFor="let company of $companies; let i = index"

Is it possible to tweak these codes so the search works or should I just code everything from scratch? If so what is the best way to do it?

0 个答案:

没有答案