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);
});
}
}
}
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?