1

I am learning Angular 2 and rather new to it, today I am trying to play with an EventEmitter in angular 2 allowing components to pass data. What I want to do, is on a click event, call a service method, which returns a promise. I then want to emit the results back up to a parent component. I have a component, with a click event on a button, that calls an injected service that returns data in the form of a Promise but within the "then" I am trying to emit the data back but my EventEmitter is undefined.

If I call the emit outside of the then, it works fine, am I missing some sort of bind to the parent scope? or is Promise the wrong thing to use here and it should be a subscribe? any help would be appreciated.

Here is the component code

import { Component, Output, Input, Injectable, EventEmitter } from '@angular/core';
import { Search } from '../Shared/models/search';
import { SearchResult } from '../Shared/models/searchResult';
import { SearchService } from '../Service/search.service';

@Component({
    selector: 'search',
    template: `<div class="col-sm-12">
                    <div class="input-group">
                        <input [(ngModel)]="search.searchText" class="form-control" placeholder="Search">
                        <span class="input-group-btn">
                        <button type="button" class="btn btn-default" (click)="searchFor()" >Go!</button>
                        </span>
                    </div>
                </div>`
})


@Injectable()
export class SearchComponent {
    constructor(private searchService: SearchService) { }

    @Input() search: Search
    @Output() errorMessage: string;
    @Output() onSearchChange = new EventEmitter<SearchResult[]>();

    searchFor() {
        this.searchService.search(this.search).then(function (results) {
            console.log("Value");
            console.log(results);
            this.onSearchChange.emit(results);
        });
    }
}
}
Michael
  • 25
  • 3
  • change `function(results)` to `results => ` – AJT82 May 15 '17 at 09:02
  • thanks @AJT_82 what does that mean? – Michael May 15 '17 at 09:07
  • Check the link in the answer :) Shortly said, with fat arrow syntax, JS uses the `this` from the outer scope. You can easily check this by using `console.log(this)` inside the `then` for the two options (`function` and `=>`), to see what scope `this` has :) – AJT82 May 15 '17 at 09:35

1 Answers1

0

To be able to keep the scope of this, you need to use fat arrow syntax, so change

this.searchService.search(this.search).then(function (results) {

to:

this.searchService.search(this.search).then(results => {

More info from the excellent answers here: How does the "this" keyword work?

Community
  • 1
  • 1
AJT82
  • 60,574
  • 21
  • 115
  • 147