Reputation: 6796
I'm stuck in something that's probably very basic... I just need to call a web server and grab my results. It used to be easy in Angular 1.
This is my component that's call the service:
import {Component, Input, OnChanges} from "angular2/core";
import {SearchService} from "../../../services/search.service";
@Component({
selector: "typeahead",
providers: [SearchService],
template: `
{{searchSvc | json}}
`,
})
export class TypeaheadComponent implements OnChanges {
@Input() txt: string;
display = false;
searchSvc;
ngOnChanges(changes: { [propName: string]: SimpleChange }) {
var search = changes['txt'].currentValue;
if (search.length > 2) {
this.display = true;
this.searchSvc = this._searchService.DoGeneralSearch();
}
else {
this.display = false;
}
}
constructor(private _searchService: SearchService) {
}
}
This is the service I'm using:
import {Injectable, OnInit} from 'angular2/core';
import {Http, HTTP_PROVIDERS, Response} from 'angular2/http';
import 'rxjs/add/operator/map';
@Injectable()
export class SearchService implements OnInit {
generalSearchResults;
ngOnInit() {
this.DoGeneralSearch();
}
constructor(private _http: Http) {
}
DoGeneralSearch() {
this._http.get('http://localhost:7000/search?q=chem')
.map((res: Response) => res.json())
.subscribe(
data => {
this.generalSearchResults = data
},
err => console.log(err),
() => console.log(this.generalSearchResults)
)
}
}
Basically I just wish to see my results displaying in my template. The results I just can see when () => console.log(this.generalSearchResults) get invoked and I notice this on my console. I see the results and the results are correct, the jSon object are correct.
What could be wrong or missing ?
Upvotes: 0
Views: 833
Reputation: 55443
export class SearchService {
constructor( private _http: Http ) {
}
DoGeneralSearch(){
return this._http.get('http://localhost:7000/search?q=chem')
.map((res:Response) => res.json());
}
}
this._searchService.DoGeneralSearch
.subscribe(res=>{
this.searchSvc =res; //make sure you get required data here.
console.log('bye');
},
(err)=>console.log(err),
()=>console.log("Done")
);
Upvotes: 0
Reputation: 202138
You need to return the observable from your DoGeneralSearch
and subscribe in the component instead:
export class SearchService {
constructor( private _http: Http ) {
}
DoGeneralSearch(){
return this._http.get('http://localhost:7000/search?q=chem')
.map((res:Response) => res.json());
}
}
For this you can leverage the async
pipe:
@Component({
selector: "typeahead",
providers: [SearchService],
template : `
{{searchSvc | async | json}}
`
})
export class TypeaheadComponent implements OnChanges {
@Input() txt: string;
display = false;
constructor(private _searchService: SearchService) {
}
ngOnChanges(changes: {[propName: string]: SimpleChange}) {
var search = changes['txt'].currentValue;
if(search.length > 2) {
this.display = true;
this.searchSvc = this._searchService.DoGeneralSearch();
}
else {
this.display = false;
}
}
}
Upvotes: 1