Before I begin, let me say that I have come across many similar questions with the same issue, but for some reason, I can't solve mine.
My setup is quite simple - a basic service and component. I'm closely following the angular2 hero tutorial. Below is my code:
location.ts
export class Location {
name: string;
type: string;
c: string;
zmw: string;
tz: string;
tzs: string;
l: string;
ll: string;
lat: string;
lon: string;
}
location-search.service.ts
import { Injectable } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Observable } from 'rxjs';
import { Location } from './location';
@Injectable()
export class LocationSearchService {
constructor(private http: Http) {}
search(term: string): Observable<Location[]> {
return this.http
.get(`api_url_i've_removed`)
.map((r: Response) => r.json().data as Location[]);
}
}
location-search.component.ts
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import { Subject } from 'rxjs/Subject';
import { LocationSearchService } from './location-search.service';
import { Location } from './location';
@Component({
selector: 'location-search',
templateUrl: 'location-search.component.html',
styleUrls: ['assets/styles.css'],
providers: [ LocationSearchService ]
})
export class LocationSearchComponent implements OnInit {
locations: Observable<Location[]>;
private searchTerms = new Subject<string>();
constructor(
private locationSearchService: LocationSearchService,
private router: Router) {}
search(term: string): void {
this.searchTerms.next(term);
}
ngOnInit(): void {
this.locations = this.searchTerms // <- ERROR HERE
.debounceTime(300)
.distinctUntilChanged()
.switchMap(term => term
? this.locationSearchService.search(term)
: Observable.of<Location[]>([]))
.catch(error => {
console.log(error);
return Observable.of<Location[]>([]);
})
}
}
I am encountering this error:
Type 'Observable<{}>' is not assignable to type 'Observable<Location[]>'.at line 29 col 9
Can you spot any obvious mistakes? Your help is greatly appreciated.