简体   繁体   中英

Angular search function only works first time

I am trying to make a search function work all the time when clicked, but unfortunately it only work the first it is clicked. Here is a picture of what I mean, when I console.log('onSubmit')' from nav.componenent.ts it gets the input string and then on the search.component.ts I get the input string from parameter and I console.log('search ngoninit') , which only gets called once, but onSubmit is getting called every time I click search. How could I make it search every time I want it to search again? I am not sure why it is doing that.

在此处输入图像描述

nav.component.ts

import { Component, OnInit, ViewChild, Output, ElementRef, EventEmitter } from '@angular/core';
import { ActivatedRoute, Router } from '@angular/router';
import { AuthService } from '../services/auth.service';

@Component({
  selector: 'app-nav',
  templateUrl: './nav.component.html',
  styleUrls: ['./nav.component.css']
})
export class NavComponent implements OnInit {
  @Output() navHeight: EventEmitter<number> = new EventEmitter();
  @ViewChild('navbar', {static: true}) navbar: ElementRef;

  searchInput: string = '';
  role: string;
  authenticated: boolean;

  constructor(private authService: AuthService, private router: Router,) {}

  ngOnInit() {
    this.navHeight.next(this.navbar.nativeElement.offsetHeight);
    this.role = localStorage.getItem('role');
    console.log(this.role);
    this.authenticated = this.authService.isAuthenticated();

    if (this.authenticated === true)
    {
      console.log('authenticated is true');
    }
  }

  

  onSubmit(inputStr: string) {
    console.log('onSubmit')
    this.router.navigate(['/search'], { queryParams: { searchStr: inputStr } });

  }

}

search.component.ts

import { Component, OnDestroy, OnInit } from '@angular/core';
import {FormBuilder, FormGroup, Validators} from "@angular/forms";
import {ActivatedRoute, Router} from "@angular/router";
import { CartService } from '../services/cart.service';
import { Product } from '../shared/product.model';
import { ProductService } from '../services/product.service';
import { Observable, Subscription } from 'rxjs';
import { map } from 'rxjs/operators';


@Component({
  selector: 'app-search',
  templateUrl: './search.component.html',
  styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit, OnDestroy {
  state$: Subscription;
  private userId: string;
  private productId: number;
  private quantity: number;
  private bodyData: any;
  private addForm: FormGroup;
  private products: Product[] = [];

  constructor(private formBuilder: FormBuilder,
    private cartService: CartService,
    private productService: ProductService,
    private router: Router,
    private activatedRoute: ActivatedRoute) { }

  ngOnInit() {
    console.log('search ngoninit')
    let searchParam = '';

    this.state$ = this.activatedRoute.queryParams.subscribe(params => {
      searchParam = params["searchStr"];
    })

    this.productService.findAll(searchParam).subscribe(resp => {
      if (resp) {
        this.products = resp.productList;
      } else {
        console.log('error finding product');
      }
    })
  }

  ngOnDestroy(){
    this.state$.unsubscribe();
  }

}

Angular only calls your ngOninit when it initializes the component. This doesn't happen every time you route to it. You need to put the findAll into your subscription to the queryParams so it refreshes your products each time you submit:

ngOnInit() {
  console.log('search ngoninit')
  let searchParam = '';

  this.state$ = this.activatedRoute.queryParams.subscribe(params => {
    searchParam = params["searchStr"];
    this.productService.findAll(searchParam).subscribe(resp => {
      if (resp) {
        this.products = resp.productList;
      } else {
        console.log('error finding product');
      }
    })
  })
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM