aboutsummaryrefslogtreecommitdiffstats
path: root/public/projects/angular-small-apps/apps/recipes/src/app/components/search-results/search-results.component.ts
blob: 4a77732e85b12ea2e5835f0609e34c587810b460 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { Recipes } from 'src/app/shared/recipes';
import { SearchService } from 'src/app/shared/services/search.service';

@Component({
  templateUrl: './search-results.component.html',
  styleUrls: ['./search-results.component.scss'],
})
export class SearchResultsComponent implements OnInit {
  recipes: Recipes[] = [];
  query: string = '';
  by: string = '';

  constructor(
    private search: SearchService,
    private router: Router,
    private route: ActivatedRoute
  ) {
    this.getRecipes();
    this.route.params.subscribe((param) => {
      this.query = param['query'];
      this.by = param['by'];
    });
  }

  ngOnInit(): void {
    if (this.recipes.length === 0) {
      const currentURL = this.router.url.replace('%20', ' ');
      const byParam = currentURL.match(/(?:by=)(\w+)/i);
      const queryParam = currentURL.match(/(?:query=)([a-zA-Z\s]*)/i);
      this.query = (queryParam && queryParam[1]) || '';
      this.by = (byParam && byParam[1]) || '';

      this.search.findResults(this.query, this.by);
    }
  }

  getRecipes(): void {
    this.search.getResults().subscribe((recipes) => {
      this.recipes = recipes;
    });
  }
}