Dinath Dinath - 11 days ago 5
TypeScript Question

Angular2 / Ionic2 : Execute $http.get within Listener

I am trying to fetch datas on scroll and fill an array of "Article[]".

httpLoadArticles() {
this.httpWSGetInit().subscribe(
articles => this.articles = articles,
err => {
console.log(err);
},
() => console.log('Searching complete')
}


And the current function.

httpWSGetInit() : Observable<Article []> {

return this.http.get(R.WEBSITE_URL_WS + this.articlesPagination)
.map((res:Response) => res.json())
.catch((error:any) => Observable.throw(error.json().error || 'Server error'));
}


Works pretty well.

But the
http.get
method is never called in
addScrollListener
.

@ViewChild(Content) content: Content;

ionViewDidLoad() {
this.content.addScrollListener(this.onPageScroll);
}

onPageScroll(event) {
this.httpLoadArticles()
}


I tried to set the
GET
as
synchronous
but it seems to not change anything. Is it a
scope
issue ? Like
addScrollListener
is a pure JS method and cannot be attached to
angular2
container ?

Answer

Yes its an scope issue. You should use Arrow function to preserve this context

ionViewDidLoad() {
    this.content.addScrollListener(() => this.onPageScroll() );
}
Comments