【问题标题】:subscription is missing properties from observable<character[]>订阅缺少 observable<character[]> 的属性
【发布时间】:2020-09-10 21:03:12
【问题描述】:

我无法修复错误,“类型 '订阅' 缺少来自类型 '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));
  }

}

编辑,添加到 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


【解决方案1】:

您已将 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,然后在需要时订阅它。

【讨论】:

    猜你喜欢
    • 2019-04-28
    • 2020-02-05
    • 2019-06-02
    • 2022-01-03
    • 1970-01-01
    • 1970-01-01
    • 2020-09-09
    • 1970-01-01
    • 2013-04-25
    相关资源
    最近更新 更多