Refresh your content with the pull-to-refresh feature in Ionic 2

latest-news.html

update function

<ion-refresher (ionRefresh)="doUpdate($event)">
    <ion-refresher-content pullingText="pull to update">

    </ion-refresher-content>
</ion-refresher>

retrieve latest news from server

<ion-list *ngSwitchCase="'latest-news'">
      <ion-card>
          <ion-item-group (click)="viewLatestNewsDetail(latest)" text-wrap *ngFor="let latest of latestNews">

            <ion-thumbnail *ngIf="latest.Preview_image1" item-start>
              <img src="{{latest.Preview_image1}}">
            </ion-thumbnail>

            <ion-card-content>
              <ion-item>
                <ion-card-title>{{latest.title}}</ion-card-title>
                <p>{{latest.news_category}}</p>
                <h3>{{latest.publish_time}}</h3>
              </ion-item>
            </ion-card-content>

          </ion-item-group>
      </ion-card>
    </ion-list>

latest-news.ts

  doUpdate(refresher){

    console.log('Begin async operation', refresher);

    setTimeout(() => {
      console.log('Async operation has ended');
      refresher.complete();
    }, 1500);

  }

retrieve latest news data

  constructor(public navCtrl: NavController, 
    public navParams: NavParams,
    public newsData:NewsDataProvider){
    this.retrieveLatestNews();
  }
  retrieveLatestNews() {
      this.newsData.getLatestNews().then(data => {
        this.latestNews = data;
      });
  }

I am attempting to update the latest news list and fetch new news data from the server. Although this code is sourced from the Ionic2 documentation, I am encountering issues.

Edit: The following code snippet is what I included in latest-news.ts. There are no errors displayed, but after performing the update, the news list remains empty.

  doUpdate(refresher){

    this.retrieveLatestNews().then(() => {
      refresher.complete();
    });

  }

  retrieveLatestNews(): Promise<any> {
      return this.newsData.getLatestNews().then(data => {
        this.latestNews = data;
      });
  }

Answer №1

Have you tried calling your getNews method from within the doRefresh function?

  constructor(public navCtrl: NavController, 
              public navParams: NavParams,
              public newsData: NewsDataProvider){
    this.getNews();
  }

  getNews(): Promise<any> {
      return this.newsData.getNews().then(data => {
        this.news = data;
      });
  }

  doRefresh(refresher) {
    this.getNews().then(() => {
      refresher.complete();
    });
  }

EDIT

After debugging the code, it was discovered that the service was storing a local copy of the data:

getNews() {
    if (this.data) {
      return Promise.resolve(this.data);
    }
    return new Promise(resolve => {
      this.http.get('servertrj.com/api/news/index/…').map(res => res.json().data).subscribe(data => {
        this.data = data;
        resolve(this.data);
      });
    });
  }

When the pull to refresh attempted to fetch new data, the service returned the same list of items. Updating the method as shown below should resolve this issue:

  getNews() {
    return new Promise(resolve => {
      this.http.get('servertrj.com/api/news/index/…').map(res => res.json().data).subscribe(data => {
        this.data = data;
        resolve(this.data);
      });
    });
  }

Alternatively, instead of creating a new promise like that, you can use the toPromise operator from RxJS:

  getNews(): Promise<any> {
    return this.http.get('servertrj.com/api/news/index/…')
                    .map(res => res.json().data)
                    .toPromise();
  }

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Converting a text file to JSON in TypeScript

I am currently working with a file that looks like this: id,code,name 1,PRT,Print 2,RFSH,Refresh 3,DEL,Delete My task is to reformat the file as shown below: [ {"id":1,"code":"PRT","name":"Print"}, {" ...

Verify that the current date is not present in Cypress

Is there a way to create a method in Cypress that displays today's date in "June 21" format and ensures that the date obtained from new Date() is not visible in the test? Here is an example of code (with typos): const today = new Date(some format); c ...

Is it possible to automatically switch to a different route in a Next.js server component after a certain period of time?

Is it possible to achieve a similar function in an async server component: displaying the ui, waiting 3 seconds, and then redirecting to another route? In a client component, you can accomplish this using: useEffect(() => { function delay(ms: number) ...

What is the best way to transfer an array to a different component?

I have an array called FidId that consists of strings, and I am looking to pass this array to another component for use. public AddSelection(layer: VectorLayer, map:Map){ this.vectorSource = layer; //start select var FidId:string[] = []; ...

Exploring the power of EJS with conditional logic

Can someone help me figure out why EJS is not evaluating to the else branch in my code? I'm using EJS version 3.1.5 with express version 4.17.1 and typescript. ReferenceError: /home/pauld/tscript/dist/views/index.ejs:12 10| </head> 11| & ...

Dynamic starting point iteration in javascript

I'm currently working on a logic that involves looping and logging custom starting point indexes based on specific conditions. For instance, if the current index is not 0, the count will increment. Here is a sample array data: const data = [ { ...

Encountering an error while using TypeScript, Mocha, and Express: "TypeError: app.address is not a

While transitioning an API from ES6 to TypeScript, a particular issue arises when attempting to run unit tests on the Express REST Endpoints: TypeError: Cannot read property 'address' of undefined The server code has been slightly adjusted for ...

What is the method to dynamically add an error to a FormGroup control using programming?

I am working with a dynamic FormGroup and I need to add an error to a form control programmatically. However, the current method I know of replaces any existing errors as shown below: this.userForm.controls.username.setErrors({ 'exists': &apos ...

guide on implementing optional URL parameters in NestJS

Currently, I am in the process of transitioning to the Nestjs library for our backend service. I am looking to create a route that includes 2 optional parameters in the URL. Here's what I have in mind: /route/:param1/config/:OptionalParam3?/:Optional ...

Error message thrown when attempting to execute foundation() function in Karma Unit Test for Angular 5 with Foundation integration

After upgrading my angular4 project to angular 5, I encountered a problem with the Foundation modal. While the modal opens as intended when running the app, running unit tests with Karma results in the following error: Failed: $(...).foundation is not a f ...

What causes error TS2339 to occur: The property 'classList' is not found on type 'never'

Currently, I am working on creating a basic component called "BackToTop" const BackToTop: React.FC = () => { const bttEl = useRef(null); function scrollHandler(): void { var bttHtmlEl: HTMLElement | null = bttEl.current; if (bttH ...

Changing function arguments in TypeScript using the spread operator

Could the Tuple spreading syntax in Typescript be utilized to consolidate these function overloads? The challenge lies in the necessity to refactor the function arguments into new types. type Type = TString | TNumber type TString = { tag: 'string&apos ...

In search of a practical and functional demonstration showcasing Electron v8 combined with TypeScript

Excuse the straightforwardness of my inquiry, as I am reaching the limits of my patience. I am in search of a practical example demonstrating the use of Electron v8 and TypeScript. The example should be simple and functional, without the need for WebPack, ...

The Vue instance seems to be unable to recognize the shims-vue.d.ts file

I encountered an issue with my Vue file. Here is the code snippet: import Vue from 'vue'; import VueRouter from 'vue-router'; export default Vue.extend({ name: 'MyComponentsName', methods: { doRedirect() { this. ...

Error in Angular 2+: Internet Explorer 11 fails to retrieve property 'call' due to undefined or null reference

I'm experiencing difficulties with Internet Explorer encountering an issue related to Webpack. My setup includes Angular-CLI 1.7.4 and Angular 5.2.10 which are the most recent versions. The error message I'm facing is as follows: SCRIPT:5007 U ...

Adding dynamic elements in Ionic2 and AngularJS can be achieved by using the correct syntax and functions provided

I am looking for a way to allow users to add elements like user inputs using ionic2/angular. In a scenario where I would typically use the following code in normal JS: function addDestination(){ var destDiv = document.getElementById('destPlac ...

Choose the object's property name using TypeScript through an interface

Consider a simplified code snippet like the following: interface MyBase { name: string; } interface MyInterface<T extends MyBase> { base: MyBase; age: number; property: "name" // should be: "string" but only p ...

Troubleshooting issue with Angular2 Dart ngFor not refreshing view with WebSockets data stream

Recently, I've been facing an issue with an Angular2 component. Whenever I use websockets, the view fails to update properly. Interestingly, everything runs smoothly when I make http requests, but I really need to ensure that the data in the view stay ...

Generating a composer method in TypeScript (Flow $Composer)

While flow supports $Compose functions, the equivalent mechanism seems to be missing in TypeScript. The closest thing I could find in TypeScript is something like https://github.com/reactjs/redux/blob/master/index.d.ts#L416-L460. Is there a native equivale ...

Is there a way to establish a connection between two excel entries using Angular?

In order to connect xlsx file records with their corresponding ids using angular, I am seeking a solution. To elaborate further: Let me provide an example for better understanding: Scenario 1 https://i.stack.imgur.com/25Uns.png Scenario 2 https://i ...