我无法修复错误,"类型"Subscription"缺少类型"Observable<字符[]>';。。。。。。任何修复错误的帮助都会很好。我还需要帮助将api返回转换为可用数据。
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));
}
}
编辑,添加到定义中。characterService.searchChar(术语((,
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', [])));
}
您已经将character$
定义为Observable
,但您正在分配订阅。
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)),
)
this.character$.subscribe(x => console.log(x));
会起作用。当您调用subscribe
时,它会返回一个Subscription
对象。如果需要,您应该先分配Observable
,然后根据需要在事后订阅它。