在Angular 6中使用ngFor进行图像的双向数据绑定

时间:2018-06-27 03:19:34

标签: typescript angular6 two-way-binding

我正在使用角度6和infinite scroll。使用http服务请求数据,我能够将数据(图像)绑定到init上的dom。但是我正在使用无限滚动获取滚动结束时的下一个记录数。在滚动我触发函数并推送到相同的数组,它反映在ts(使用调试器检查)。但不能绑定到HTML。可能重复,但是没有解决方案对我有帮助。并且请提供正确的方法来实现角度6中的去抖动方法,任何人都可以帮忙
HTML

<section class="main-container"  infiniteScroll infiniteScrollUpDistance]="1" 
[infiniteScrollThrottle]="300" (scrolled)="onScroll($event)">
 <ul class="grid-wrap">

  <li *ngFor="let image of flickrImages">
    <img [attr.src]="image.url_m" alt="Image not found" onerror="this.src='https://i5.walmartimages.com/asr/f752abb3-1b49-4f99-b68a-7c4d77b45b40_1.39d6c524f6033c7c58bd073db1b99786.jpeg?odnHeight=450&odnWidth=450&odnBg=FFFFFF';" >
  </li>
</ul>
</section>

ts

reqObj : any = {
   per_page : 5,
   pageNo: 1,
   query: ''
 }
getImages(fromScroll){
this.reqObj['query'] = this.searchKeyword ? this.searchKeyword : '';
this.flickrService.getImages(this.reqObj).subscribe((res) => {
  if(res && res['stat'] ==='ok'){
    if(fromScroll){
      this.flickrImages.push(...res['photos']['photo'])          
      this.reqObj.pageNo++;
    } else{
      this.flickrImages = res['photos']['photo'];
      this.totalPages = res['photos']['pages']
    }
  }
 },(error) => {
   console.log(error);
 });
}
onScroll(ev) {
  if(ev.currentScrollPosition>=document.documentElement.scrollHeight && 
this.reqObj.pageNo < this.totalPages ){
    this.getImages(true);
   }
}



服务

import { Injectable } from '@angular/core';
import { HttpClient, HttpHeaders } from '@angular/common/http';
// import 'rxjs/add/operator/map';

@Injectable({
providedIn: 'root'
})
 export class FlickrService {
constructor(private http:HttpClient) { }
  ApiUrl = "https://api.flickr.com/services/rest/?extras=url_m&api_key=4df09ecd4fb22d6b29e03658dfbca36f&format=json&nojsoncallback=1";
  getImages(reqObj){
    if(reqObj.query){
      return this.http.get(this.ApiUrl+'&per_page='+ reqObj.per_page+'&text='+reqObj.query+'&page='+reqObj.pageNo+'&method=flickr.photos.search');
    } else {
      return this.http.get(this.ApiUrl+'&per_page='+ reqObj.per_page+'&page='+reqObj.pageNo+'&method=flickr.photos.getRecent');
    }

  }
}

0 个答案:

没有答案