前言:我知道还有很多其他问题也有同样的错误,但我似乎仍然无法弄清楚我自己的问题。
我有一个简单的服务和另一个简单的组件。我正在尝试非常严格地遵循 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;
}
位置搜索.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[]>([]);
})
}
}
我不断收到错误:
Type 'Observable<{}>' is not assignable to type 'Observable<Location[]>'.at line 29 col 9
我做错了什么明显的事情吗?感谢您的帮助
最佳答案
我无法告诉你确切的问题,但我也为这个问题苦苦挣扎过几次!
这是 .switchMap()
的问题。我不知道这是 typescript 问题还是什么..
也许只是打字文件不好..
你必须转换它:
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[]>([]);
})
}
关于angular - 类型 'Observable<{}> is not assignable to type ' 可观察',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40254268/