Is it possible to fetch all data on initialization using observable search in Angular 2? (Closed)

I am currently developing a personal app and facing an issue with retrieving user data when initializing my component for the first time. It seems that my searchTerms are causing an obstacle in processing the subject string properly. I have attempted using this.searchTerms.next(''); in the ngOnInit method but it did not work as expected. Interestingly, if I enter a user name and then delete it, the list of users appears due to the execution of the else block for switchMap.

Overview of My Component:

export class UserComponent implements OnInit {

  users: Observable<User[]>;
  private searchTerms = new Subject<string>();

  getUsers(): void {
    this.users = this.searchTerms
      .debounceTime(300)        // wait 300ms after each keystroke before considering the term
      .distinctUntilChanged()   // ignore if next search term is same as previous
      .switchMap(term => term   // switch to new observable each time the term changes
        // return the http search observable
        ? this.userService.search(term)
        // or the observable of all users if there was no search term
        : this.userService.search(''))
      .catch(() => {
        return Observable.of<User[]>([]);
      });
  }

  ngOnInit(): void {
    this.getUsers();
  }

  search(term: string): void {
    // Push a search term into the observable stream.
    this.searchTerms.next(term);
  }

My Template Structure:

...
<h4>User Search</h4>
    <input #userSearchBox id="user-search-box" (keyup)="search(userSearchBox.value)" />
...
<div *ngFor="let user of users | async" class="input-group">
...

Answer №1

Maybe this is closer to what you're looking for

import 'rxjs/add/operator/startWith';

export class UserComponent implements OnInit {

  searchTerms = new Subject<string>();

  searchTerm$ = this.searchTerms.asObservable().startWith('');

}

Answer №2

Solved my issue by implementing the cycle method ngAfterViewInit and including the code below:

ngAfterViewInit(): void {
  this.searchTerms.next('');
}

The problem stemmed from a timing issue where I was invoking the subscription too early. Appreciate the assistance provided.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Exception occurs when arrow function is replaced with an anonymous function

Currently, I am experimenting with the Angular Heroes Tutorial using Typescript. The code snippet below is functioning correctly while testing out the services: getHeroes() { this.heroService.getHeroes().then(heroes => this.heroes = heroes); } H ...

"Error encountered: Unable to resolve dependency tree" message appears when attempting to run npm install

Encountering dependency errors while trying to execute the npm install command for my Angular application. As a newcomer to TypeScript and Angular, I'm unsure of the next steps to take. Any suggestions? Attempted solutions include clearing the npm ca ...

Leveraging TypeScript in tandem with React to create stateless components

I'm curious about the distinctions between these variations, in a scenario where state is not being used: 1. export class SkillList extends React.Component<SkillListProps> {} 2. export class SkillList extends React.Component<SkillListProps, ...

Develop a custom class for importing pipes in Angular 4

Currently, I am working on creating a pipe that will replace specific keywords with the correct strings. To keep this pipe well-structured, I have decided to store my keywords and strings in another file. Below is the code snippet for reference: import { ...

Is it possible to maintain component data in Angular while also incorporating dynamic components?

All the code you need can be found here: https://stackblitz.com/edit/angular-keep-alive-component?file=src/app/app.component.ts Is it possible to maintain the state of entered values when switching components? I am currently utilizing dynamic component r ...

Create keys for accessing objects based on props

I'm facing challenges with dynamisation in Typescript. I understand that TS primarily works statically, but there are instances where I need to access an object dynamically and can't do so directly through generics because the values are dynamica ...

Ensure that the ngOnChange is triggered after the BehaviorSubject emits a true value twice

I am currently developing an Angular 5 application. One of the components in my project is a dropdown component ( containing the following code in the html file, dropdown.component.html <p-dropdown [options]="data" [(ngModel)]="selectedFilterValue" pl ...

What is the process of generating a new type in TypeScript based on another type with a distinct property of a different type?

I am defining a type as follows: type Period = 'Monthly' | 'Yearly' type Cycle = { period: Period, price: number } Now, I am looking to modify this type so that the 'period' property can also accept an empty string: t ...

Creating a mongoose authentication model

I encountered an issue when attempting to integrate mongoose passport into my schema, resulting in the following error message: export interface IUserModel extends IUser, Document { }; export let userSchema = new Schema({ username: { type: String, re ...

Extract JSON values based on a given condition

I am working on a Typescript project that involves an array and a JSON object. I need to extract the value of a property from the object based on another property's value being in the array. Here is the array: let country: string[] = [ 'AR' ...

Integrating one service into another allows for seamless access to the imported service's properties and methods within an Angular

After reviewing the content at https://angular.io/guide/dependency-injection-in-action, it appears that what I am trying to achieve should be feasible. However, I encounter this error when attempting to invoke a method on my injected service from another s ...

"Firebase function fails to return Typescript class variable, resulting in 'undefined'

Being someone with a background in python/golang, I am now delving into ionic2. There seems to be an issue that I can't quite figure out due to my current level of knowledge in this stack. Perhaps I just need a way to reference the outer scope of this ...

Tips on altering the positioning of a <a-entitiy> when clicked

Is there a way to make an object despawn on click if the cursor is on top of it, then respawn at a new position upon clicking? I attempted to achieve this using the aframe-event-set-component (https://www.npmjs.com/package/aframe-event-set-component), but ...

What is the best way to manage various Firebase Cloud Function API endpoints for different environments, such as DEV and PROD?

I am currently developing an Angular application hosted on Firebase. I am facing a question regarding the best approach to handle the same application being deployed in two different environments (DEV and PROD), each associated with a separate Firebase pr ...

Tips for resolving the <!--bindings={ "ng-reflect-ng-for-of": "" }--> bug

Just starting out with Angular and I am having some issues with event binding and property binding in my game-control component. I have a button that, when clicked, adds numbers to an array using setInterval method. I am also passing data between compone ...

Encountering an issue while adding types to a custom component in a Formik form: Error message states that type 'T[keyof T]' cannot be assigned to type 'string'

I'm delving into TypeScript for the first time and attempting to incorporate it into a previous project as a learning exercise. I've hit a roadblock while trying to add types to a custom form field component in Formik, encountering an error mess ...

TSLint has detected an error: the name 'Observable' has been shadowed

When I run tslint, I am encountering an error that was not present before. It reads as follows: ERROR: C:/...path..to../observable-debug-operator.ts[27, 13]: Shadowed name: 'Observable' I recently implemented a debug operator to my Observable b ...

Problem with dynamic page routes in Next.js (and using TypeScript)

Hi everyone, I'm currently learning next.js and I'm facing an issue while trying to set up a route like **pages/perfil/[name]** The problem I'm encountering is that the data fetched from an API call for this page is based on an id, but I wa ...

The function getStaticPaths() will generate a 404 error, indicating that the page

I have encountered a persistent issue with the getStaticPaths() function throwing a 404 error. After investigating, I suspect that the problem may lie in the implementation of the getAllPostIds() function, which is supposed to generate an array of object ...

Utilizing the spread operator in Typescript to combine multiple Maps into a fresh Map leads to an instance of a clear Object

Check out the code below: let m1 = new Map<string, PolicyDocument>([ [ "key1", new PolicyDocument({ statements: [ new PolicyStatement({ actions: [&q ...