Angular 9: Subscribing triggering refreshing of the page

I've been working on an Angular 9 app that interacts with the Google Books API through requests.

The issue I'm facing is that whenever the requestBookByISBN(isbn: string) function makes a .subscribe call, it triggers a page refresh which I'm trying to prevent.

  private callAPI(isbn: string): Observable<GoogleBook[]> {

    return this.httpClient
        .get<{ results: GoogleBook[] }>
        (`https://www.googleapis.com/books/v1/volumes?q=${isbn}&key=${ApiLookupService.API_KEY}`)
        .pipe(map(matches => matches.results || []));
  }

  public requestBookByIsbn(isbn: string): GoogleBook[] {
    const bookResults: Observable<GoogleBook[]> = this.callAPI(isbn);
    let books: GoogleBook[] = [];
    bookResults.subscribe(data => books = data);
    return books;
  }

To provide more context, below is a snippet of the component.ts file containing relevant code snippets:

import {Component, OnInit} from '@angular/core';
import {BookServiceImpl} from '../../shared/Book/service/book.service.impl';
import {CopyServiceImpl} from '../../shared/Copy/service/copy.service.impl';
import {AuthorServiceImpl} from '../../shared/Author/service/author.service.impl';
//more imports

@Component({
    selector: 'app-addbook',
    templateUrl: './addbook.component.html',
    styleUrls: ['./addbook.component.css']
})
export class AddbookComponent implements OnInit {
    // various properties and methods are defined here
    
    constructor(private bookService: BookServiceImpl,
                private copyService: CopyServiceImpl,
                private authorService: AuthorServiceImpl,
                //more dependencies injected 
                ) {
    }

    // various methods such as initAuthors, findAuthors, isbnLookUp, onSubmit are implemented here
    
}

It's possible that conflicts with other subscribe calls might also be contributing to the issue.

Answer №1

It's possible that the reason for the refreshing behavior is due to the asynchronous nature of bookResults.subscribe. This means you are initially returning an empty array and then at some point updating it with the full data.

To address this issue, you have two options: utilize RXjs or promises:

RXjs approach:

  public requestBookByIsbn(isbn: string): GoogleBook[] {
    return this.callApi(isbn);
  }

The component calling requestBookByIsbn can then subscribe and set the data in the component when ready.

Promise option:

  public async requestBookByIsbn(isbn: string): GoogleBook[] {
    const bookResults: Promise<GoogleBook[]> = this.callAPI(isbn).toPromise();
    return await bookResults;
  }

The refresh may be happening outside of the code snippet shown.

If you are redirecting to '/login' to verify user login status, consider adding the current path as history state or a query parameter during the redirect. Then, redirect back to that path after completing the login process instead of directing to '/'.

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

Angular 5 experiences a single catchError event for two unsuccessful http calls

I recently implemented Observable.zip in my code to manage multiple observables concurrently. Observable.zip(observable1, observable2).subscribe(([res1, res2]) => doStuff()) The observables observable1 and observable2 represent HTTP requests, and I ha ...

Error: The selected module is not a valid top-level option

I am facing an issue while using the babel-loader. I have removed all irrelevant code and just kept the error-related portion. What could be causing this problem? module.exports = merge(baseWebpackConfig, { ... module: { rules: [ ...

How can you trigger a 'hashchange' event regardless of whether the hash is the same or different?

Having a challenge with my event listener setup: window.addEventListener('hashchange', () => setTimeout(() => this.handleHashChange(), 0)); Within the handleHashChange function, I implemented logic for scrolling to an on-page element whil ...

Having trouble with the npm install command for setting up the Angular dual list box feature

I attempted to run the npm i angular-dual-listbox --save command, but encountered numerous errors indicating version discrepancies despite having version 8.2.14. I referred to this article: npmjs. The error log is as shown below: C:\GUNEET KAUR\P ...

Step-by-step tutorial on how to enable app logout functionality using Node.js and Okta

I have created a web app using Okta with OIDC and Node Express for user authentication. I want users to be able to log out of my app without logging out of the company Okta, which is used for multiple websites. Okta recommends this approach on their websit ...

Tips for navigating the material ui Expanded attribute within the Expansion Panel

After looking at the image provided through this link: https://i.stack.imgur.com/kvELU.png I was faced with the task of making the expansion panel, specifically when it is active, take up 100% of its current Div space. While setting height: 100% did achi ...

Error encountered when initializing a variable within the constructor of a TypeScript file in Angular 4

This is the content of my app.component.html file PL Auth Username: Password : Generate OTP Enter OTP : Login This is the code in my app.component.ts file import { Component, OnInit } from '@angular/core' ...

Can you delve into the origin of the term Modal in the context of Angular and web development?

My understanding of a Modal is that it is a webpage component that opens separately from the main page in order to maintain continuity. Am I correct? I am curious as to why it is referred to as a Modal. Could it be short for modularity? Meaning that vari ...

The sequence of operations when assigning in Typescript with || and utilizing the array .find method

I need to ensure that the operations in my assignment are happening in a specific sequence. As far as I can tell, it should be following the order listed below. However, I have not been able to locate any documentation on TypeScript that definitively confi ...

TypeScript encountered an unexpected { token, causing a SyntaxError

Despite multiple attempts, I can't seem to successfully run my program using the command "node main.js" as it keeps showing the error message "SyntaxError: Unexpected token {" D:\Visual Studio Code Projects\ts-hello>node main.js D:&bsol ...

Deploy your Angular2 application with a specified base URL

I am embarking on the journey of Angular2 web app development. After successfully creating an Angular2 application using angular-cli, I am now faced with the challenge of deploying it to my Tomcat server. Following the ng build command, a dist folder was ...

Develop your project with Angular 2 using the powerful Angular CLI build tool

Hello there! I am new to Angular 2 and recently developed a small project with the help of angular-cli for packaging. The dist folder was generated successfully. However, when I deployed the app to the server and tried to access the index.html page, it co ...

Currently honing my skills in Angular 2, but encountering an error stating "Bindings cannot contain assignments."

<app-employeecount [all]= "gettotalemployeescount()" <app-employeecount [all]= "gettotalemployeescount()" [male]= "gettotalmaleemployeescount()" [female]="gettotalfemaleemployeescount()" (on ...

An issue has occurred: Unable to locate a supporting object 'No result' of type 'string'. NgFor is only compatible with binding to Iterables like Arrays

I am attempting to utilize this code to post data from a web service. service.ts public events(id: string): Observable<Events> { ...... return this.http.post(Api.getUrl(Api.URLS.events), body, { headers: headers }) .map((re ...

What causes the issue of Angular 9 routing breaking upon page refresh?

I have deployed my Angular 9 application on Heroku and everything is working perfectly. However, when I refresh the page or copy/paste a link, I get an error message saying "Cannot GET /XXX/XXX". Only the root link seems to work! Initially, I can navigate ...

Generating typescript definitions for Polymer 2.4 packages

According to information provided in the latest announcement, declarations are now automatically generated from the Polymer source. I recently upgraded to Polymer 2.4 and encountered an error during project build due to a missing typescript definition fil ...

Implementing a string replacement within an array of objects using TypeScript

I have a collection of array objects displayed below [ { "subjectID": 1 "Chosen" : "{subjectsChosen:Python,java,Angular}" "password": "{studentpw:123456abcd}" }, { "subjectID": 2 ...

Set the enumeration value to a variable

I am facing a problem where it seems impossible to do this, and I need help with finding a solution enum Vehicles { BMW='BMW', TOYOTA='Toyota' } class MyVehicles { public vehicleName: typeof Vehicles =Vehicles; } const veh ...

Unlocking the potential for over 1000 search results using the GitHub API

Is there a way to display more than 1000 search results when listing the most starred Github repositories created in the last 30 days? I keep getting an error message that says: { "message": "Only the first 1000 search results are available", "documen ...

Exploring the latest features of Angular 2's ngModel form to track user selections

Consider this form: <form name="setQuestions_form" (ngSubmit)="set_questions()"> <ng-select [multiple]="true" [options]="questions" [(ngModel)]="selectedQuestions" name="selectedQuestions"></ng-select> <button>send</butt ...