Search code examples
angularangular2-servicesangular2-http

Angular 2 Basic http service request


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 ?


Solution

  • 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;
        }
      }
    }