Как отключить кеширование запросов или добавить обновление в приложение ionic 3? - PullRequest
0 голосов
/ 22 октября 2018

У меня проблема с моим приложением ionic: на ionViewWillEnter () я запрашиваю сервер с запросом GET для получения данных.Если я открываю страницу в первый раз, запрос отправляется.Если это второе открытие, приложение читает кэш и не отправляет запрос.Эта проблема существует только на устройстве.Любая идея ?Спасибо.

РЕДАКТИРОВАТЬ: Я использую эту версию: @ ionic / app-scripts: 3.2.0Платформы Cordova: IOS 4.5.5Ionic Framework: ionic-angular 3.9.2

Все запросы поступают на перехватчик:

import { Injectable, NgModule} from '@angular/core';

import { Observable } from 'rxjs/Observable';
import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HttpHeaders} from '@angular/common/http';
import {Globals} from './globals';
@Injectable()
export class HttpsRequestInterceptor implements HttpInterceptor {
headers : HttpHeaders;
  constructor(private globals: Globals){}
 intercept(
   req: HttpRequest<any>,
   next: HttpHandler): Observable<HttpEvent<any>> {
     if(localStorage.getItem('jwt')){
       this.headers = new HttpHeaders({'Authentication':localStorage.getItem('jwt'),'Cache-Control':['no-cache','no-store'],'Pragma':'no-cache','Expires': '0'});
   }else{
     this.headers = new HttpHeaders({'Authentication':''});
   }
     const dupReq = req.clone({ headers: this.headers });
     return next.handle(dupReq);
   }
};

У меня все CORS включены на моем сервере.

В моем контроллере Iсделать это:

import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams,LoadingController } from 'ionic-angular';
import {UserService} from '../../providers/user-service';
import {AlertService} from '../../providers/alert-service';
import { TranslateService } from '../../app/translate';

@IonicPage()
@Component({
  selector: 'page-user-messages',
  templateUrl: 'user-messages.html',
})
export class UserMessagesPage {
messagesList;
  constructor(public navCtrl: NavController, public navParams: NavParams,public translateService:TranslateService,
    public alertService : AlertService, private userService : UserService,public loadingCtrl: LoadingController) {

  }
/**
* Show user's messages
**/
  ionViewWillEnter() {
    let loader = this.loadingCtrl.create({
      content: this.translateService.instant('text','loadingText'),
    });
    loader.present().then(() => {
    this.userService.getMyMessages().subscribe(jsonResponse=>{
      if(jsonResponse.success==true){
        this.messagesList = jsonResponse.rows;
      }else{
        this.alertService.showAlert(this.translateService.instant('error','title'),jsonResponse.msg);
      }
      loader.dismiss();
    },error => {
      this.alertService.showAlert(this.translateService.instant('error','title'),error);
      loader.dismiss();
    });
    });
  }

}

И, наконец, поставщик:

import { Injectable } from '@angular/core';
import { HttpClient,HttpParams } from '@angular/common/http';
import { Globals} from '../app/globals';
import 'rxjs/add/operator/map';
import {Observable} from 'rxjs/Observable';
import {User} from '../app/models/user';
import {JsonResponse} from '../app/models/json-response';
@Injectable()
export class UserService {

  constructor(private httpClient : HttpClient, private globals: Globals){}

  public getMyMessages() : Observable<any>{
    return this.httpClient.get("myurl");
  }

}

1 Ответ

0 голосов
/ 30 октября 2018

Итак, я наконец-то нашел решение: в вашем .htaccess установите заголовок для Cache Control следующим образом:

Header set Cache-Control "private, s-maxage=0, max-age=0, max-age=0, must-revalidate"
...