Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
805 views
in Technique[技术] by (71.8m points)

angular - Pipe Async - Error trying to diff '[object Object]'. Only arrays and iterables are allowed

I was using the Tour Heroes tutorial: https://angular.io/tutorial/toh-pt6#search-by-name to create my own search bar. However the diff '[object Object]' error appeared and although lots of answers say that I need to convert the object in array form, in the tutorial, it says the async pipe take cares of that for me so i don't have to subscribe.

Thank you in advance!

Error message

offer-search.component.html

    <input #searchBox id="search-box" (keyup)="search(searchBox.value)" />

      <ul class="search-result">
        <li *ngFor="let offer of offers$ | async" >
            {{offer.name}}
        </li>

offer-search.component.ts

...
import { Offer } from '../model/offer';
import { OfferService } from '../offer.service';

@Component({
  selector: 'app-offer-search',
  templateUrl: './offer-search.component.html',
  styleUrls: ['./offer-search.component.css']
})
export class OfferSearchComponent implements OnInit {
  @Input('offerP') offerProperty: string;

  offers$: Observable<Offer[]>;
  private searchTerms = new Subject<string>();

  constructor(private offerService: OfferService) {}

  // Push a search term into the observable stream.
  search(term: string): void {
    this.searchTerms.next(term);
  }

  ngOnInit(): void {
    this.offers$ = this.searchTerms.pipe(
      // wait 300ms after each keystroke before considering the term
      debounceTime(300),

      // ignore new term if same as previous term
      distinctUntilChanged(),

      // switch to new search observable each time the term changes
      switchMap((term: string) => this.offerService.searchOffersByProperty(term, this.offerProperty)),
    );
  }
}

offer.service.ts

...
  searchOffersByProperty(term: string, prpty: string): Observable<Offer[]> {
    if (!term.trim()) {
      // if not search term, return empty hero array.
      return of([]);
    }
    let searchURL = this.url + `/offers/?foodOfferer=${this.authService.credential.foodOfferer.id}&${prpty}=${term}`;
    return this.http.get<any>(searchURL, {
      headers: this.headers,
      responseType: 'json',
    }).pipe(catchError(this.handleError('searchOffersByProperty', '')));
  }

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

As the docs state

The AsyncPipe subscribes to an Observable automatically so you won't have to do so in the component class.

which means you don't have to manually subscribe in your component. Manually subscribing would look something like

// ts
this.searchTerms.pipe(
  debounceTime(300),
  distinctUntilChanged(),
  switchMap((term: string) => 
      this.offerService.searchOffersByProperty(term, this.offerProperty)),
  )
  .subscribe(offers => this.offers = offers);

// html
<li *ngFor="let offer of offers">
  {{offer.name}}
</li>

The async pipe does not do data transformation. For this you need to convert the result from your api (currently an object) to an array using the rxjs map method.

// ts
this.offers$ = this.searchTerms.pipe(
  debounceTime(300),
  distinctUntilChanged(),
  switchMap((term: string) => this.offerService.searchOffersByProperty(term, this.offerProperty)),
  map(results => {
      // do transformation here
      let resultsArray = ...;
      return resultsArray;
  })
);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...