Angular headless CMS Wordpress API request caches on .get(`https://website.com/wp-json/wp/v2/pages/${pageId}`)

23 Views Asked by At

I am using Wordpress as a headless CMS on an Angular app

export class WordpressService {
  private wpUrl = 'https://wp.vsalininkai.lt/';

  constructor(private http: HttpClient) { }

  getPage(pageId: number): any {
    const url = `${this.wpUrl}wp-json/wp/v2/pages/${pageId}`;
    return this.http.get(url).pipe(catchError(this.errorHandler));
  }

  errorHandler(error: HttpErrorResponse) {
    return new Observable((observer: Observer<any>) => {
      observer.error(error);
    });
  }
}

export class CommonPageComponent implements OnInit {
  @Input() pageId: number;
  section: CommonSection = new CommonSection('', '');
  loading: boolean = false;

  constructor(private wordpressService: WordpressService,
    private sanitizer: DomSanitizer) {}

  ngOnInit(): void {
    this.loading = true;

    this.wordpressService.getPage(this.pageId)
    .subscribe(
      (res: any) => {
        console.log(res);
        this.section.title = res.title.rendered;
        this.section.html = res.content.rendered;
        this.loading = false;
      },
      (err: any) => {
        console.log(err);
        this.loading = false;
      }
    );
  }

  sanitizeHtml(htmlContent: string): SafeHtml {
    return this.sanitizer.bypassSecurityTrustHtml(htmlContent);
  }
}

When the Wordpress page gets updated it doesn't change on the angular app and it seems to only change after disabling cache, is there a way to make this work without having to click disable cache on the inspect element network tab?

Tried passing in HttpHeaders

export class WordpressService {
  private wpUrl = 'https://wp.vsalininkai.lt/';

  constructor(private http: HttpClient) { }

  getPage(pageId: number): Observable<any> {
    const url = `${this.wpUrl}wp-json/wp/v2/pages/${pageId}`;

    const headers = new HttpHeaders({
      'Cache-Control': 'no-cache',
      'Pragma': 'no-cache',
      'Expires': 'Sat, 01 Jan 2000 00:00:00 GMT'
    });

    return this.http.get(url, {headers}).pipe(catchError(this.errorHandler));
  }

  errorHandler(error: HttpErrorResponse) {
    return new Observable((observer: Observer<any>) => {
      observer.error(error);
    });
  }
}

but it gives me CORS errors because Wordpress API doesn't allow cache-control, pragma or expires headers.

0

There are 0 best solutions below