1

I am using Angular7, NgBootstrap 4. I have a input field with Typeahead directive.

When I follow custom search function format as written in documentation, works fine. When I try to modify format, I get an error:

I get this error:

core.js:12584 ERROR TypeError: Cannot set property 'searching' of undefined

What I am doing wrong?

This is working:

 search = (text$: Observable<string>) =>
    text$.pipe(
      debounceTime(300),
      distinctUntilChanged(),
      tap(() => this.searching = true),
      switchMap(term =>

        this.searchService.fetchData(term).pipe(
          tap(() => this.searchFailed = false),
          catchError(() => {
            this.searchFailed = true;
            return of([]);
          }))
      ),

      tap(() => this.searching = false)

    );

this is not working:

search = function (text$: Observable<string>) {

    return text$.pipe(
      debounceTime(300),
      distinctUntilChanged(),
      tap(() => this.searching = true),
      switchMap(term =>

        this.searchService.fetchData(term).pipe(
          tap(() => this.searchFailed = false),
          catchError(() => {
            this.searchFailed = true;
            return of([]);
          }))
      ),

      tap(() => this.searching = false)

    );

  }
Luke1988
  • 1,850
  • 2
  • 24
  • 42
  • Possible duplicate of [How to access the correct \`this\` inside a callback?](https://stackoverflow.com/questions/20279484/how-to-access-the-correct-this-inside-a-callback) – JB Nizet Nov 09 '18 at 12:26
  • 1
    You're using non-arrow functions, which are not bound to `this`. Just use arrow functions, as the examples show. – JB Nizet Nov 09 '18 at 12:27
  • Thanks. Reason, why I use non-arrow function is that I want to add custom functions calls before text$.pipe .. is returned, however, your answer gave me right direction. Thanks! – Luke1988 Nov 09 '18 at 12:52

1 Answers1

1

Thanks to JB Nizet who gave me right direction. This is working code (see curly brackets in the first and last line)

search = (text$: Observable<string>) => {

    // do some logic before text$.pipe call
    console.log(text$);


    text$.pipe(
      debounceTime(300),
      distinctUntilChanged(),
      tap(() => this.searching = true),
      switchMap(term =>

        this.searchService.fetchData(term).pipe(
          tap(() => this.searchFailed = false),
          catchError(() => {
            this.searchFailed = true;
            return of([]);
          }))
      ),

      tap(() => this.searching = false)

    );

}
Luke1988
  • 1,850
  • 2
  • 24
  • 42