前言:我知道有很多其他问题与这个完全相同的错误,但我似乎仍然无法弄清楚我自己的问题。
我有一个简单的服务,另一个简单的组件。我正在密切关注angular2英雄教程,这是我的代码:
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;
}
位置的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[]);
}
}
位置的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[]>([]);
})
}
}
我一直收到错误:
Type 'Observable<{}>' is not assignable to type 'Observable<Location[]>'.at line 29 col 9
我做错了什么吗?感谢您的帮助
答案 0 :(得分:1)
我无法告诉你确切的问题,但我也在这几次挣扎!
这是.switchMap()
的问题。如果它是打字稿问题或什么......
也许只是打字文件很糟糕..
你必须施展它:
ngOnInit(): void {
this.locations = <Observable<Location[]>>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[]>([]);
})
}
或(正如您所提到的)将您的函数switchMap()
和catch()
与类型声明一起使用,如下所示:
ngOnInit(): void {
this.locations = this.searchTerms // <- ERROR HERE
.debounceTime(300)
.distinctUntilChanged()
.switchMap<Observable<Location[]>>(term => term
? this.locationSearchService.search(term)
: Observable.of<Location[]>([]))
.catch<Observable<Location[]>>(error => {
console.log(error);
return Observable.of<Location[]>([]);
})
}