0

I was following this tutorial and reached the below code with searches wikipedia for a given term. The below code works fine and fetches the search result from wikipedia.

export class WikiAppComponent {
      items: Array<string>;
      term = new Control();

      constructor(public wikiService: WikiService) { }

      ngOnInit() {
        this.term.valueChanges.debounceTime(400).subscribe(term => {
          this.wikiService.search(term).then(res => {
             this.items = res;
          })
        });
      }
 }

But when I refactored the and moved the code for search to a separate function it is not working. this.wikiService inside the search function is going undefined. Can you throw some light on why it is going undefined?

export class WikiAppComponent {
      items: Array<string>;
      term = new Control();

      constructor(public wikiService: WikiService) { }

      search(term) {
        this.wikiService.search(term).then(res => {
          this.items = res;
        });
      }

      ngOnInit() {
        this.term.valueChanges.debounceTime(400).subscribe(this.search);
      }
    }
1
  • 1
    Could you open a debugger in your browser, set a breakpoint in the search method and see what the definition of 'this' is? TypeScript does its best to emulate real class encapsulation, but when you're working with function pointers, the javascript 'this' issue tends to surface, still. Commented May 24, 2016 at 4:51

1 Answer 1

2

You are having a scope issue, "this" inside your callback is not refering to your page. Change your function callback like this:

this.term.valueChanges.debounceTime(400).subscribe( 
   (term) => {
      this.search(term);
   });
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.