【发布时间】:2020-09-10 21:03:12
【问题描述】:
我无法修复错误,“类型 '订阅' 缺少来自类型 'Observable
export class CharacterSearchComponent implements OnInit {
// sets characters$ as an observable
character$: Observable<Character[]>;
private subscriptions: Subscription[] = [];
// sets private method for searching
private searchTerms = new Subject<string>();
constructor(
// sets private method for using character.service
private characterService: CharacterService
) { }
// pushes search terms into the observable
search(term: string): void{
this.searchTerms.next(term);
}
ngOnInit(): void {
this.character$ = this.searchTerms.pipe(
// wait after keystroacks to reduce frequent http pull attempts
debounceTime(300),
// ignore if same as previous turm
distinctUntilChanged(),
// switch to new search if the term changed
switchMap((term: string) => this.characterService.searchChar(term)),
).subscribe(x => console.log(x));
}
}
编辑,添加到 this.characterService.searchChar(term)) 的定义中,
searchChar(term: string): Observable<Character[]> {
if (!term.trim()) {
// if no match, return nothing
return of([]);
//console.log();
}
return this.http.get<Character[]>(`${this.characterUrl}/?search=${term}`).pipe(tap(x => x.length?
this.log(`found characters matching "${term}"`) :
this.log(`Sorry, cant find a character matching "${term}"`)),
catchError(this.handleError<Character[]>('searchChar', [])));
}
【问题讨论】:
-
请提供
this.characterService.searchChar(term)的定义 -
searchChar(term: string): Observable
{ if (!term.trim()) { // 如果不匹配,则不返回 return of([]); //console.log(); } 返回 this.http.get ( ${this.characterUrl}/?search=${term}).pipe(tap(x => x.length? this.log(found characters matching "${term}") : this.log(Sorry, cant find a character matching "${term}")), catchError( this.handleError('searchChar', []))); }
标签: angular observable subscription