簡體   English   中英

訂閱缺少 observable 的屬性<character[]>

[英]subscription is missing properties from observable<character[]>

我無法修復錯誤,“類型‘訂閱’缺少類型‘Observable<Character[]>’中的以下屬性;......修復錯誤的任何幫助都會很好。我還需要幫助將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));
  }

}

編輯,在 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', [])));
    }

您已將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 ,然后根據需要在事后訂閱它。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM