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

Issue with React TypeScript: Only the first state update takes effect, despite multiple updates being made

Check out this sandbox I created here. When you leave any of the form inputs blank, I should be seeing 3 errors but instead, I only get one. Can anyone explain why this is happening? import React, { ChangeEvent, useState } from 'react'; import { ...

Can someone confirm if I am importing this png file correctly? I am encountering an error with Vite, here is my code

Error: TypeScript+ React + Vite [plugin:vite:import-analysis] Failed to find import "./assets/heropic.png" in "src\components\Hero.tsx". Are you sure the file exists? Hello fellow developers! I am new to working with react and typescript. Curren ...

Error: Code cannot be executed because the variable "sel" has not been defined in the HTML element

Every time I try to click on the div, I encounter an error message stating 'Uncaught ReferenceError: sel is not defined at HTMLDivElement.onclick' I am currently developing with Angular 8 and this error keeps popping up. I have read through simil ...

Why did the developers of Angular 2+ choose to use JavaScript Objects instead of Typescript Classes for defining Router routes?

When working with the Angular 2+ Router, the standard approach involves defining routes in the app-routing module. app-routing.module.ts import { NgModule } from '@angular/core'; import { Routes, RouterModule } from '@angular/router'; ...

The NullInjectorError is thrown when the Angular service providedIn: root is imported from a library

After moving my service into a separate npm package, I encountered an issue where the service was marked to be provided in the root injector but resulted in a NullInjectorError when trying to use it in my app. To solve this problem, I had to include Quer ...

Issue with Angular2 wysiwyg component failing to submitThe Angular2

I'm currently in the process of familiarizing myself with angular2 by developing a sleek wysiwyg component. However, I seem to have reached an obstacle at this point. Below is the code I've been working on: The form that I am utilizing for testi ...

The compatibility between TypeScript and the Node.js crypto module is currently not fully optimized

Incorporating encryption into my project using vuejs and typescript has been a challenge. I managed to implement it in the .vue file successfully, but encountered an issue when trying to write the encryption into a typescript class. The mocha test runs fin ...

Issue encountered in cdk-virtual-scroll-viewport upon modifying the item array

Encountering an issue with a list of products displayed in a virtual scroll. The problem arises when the array of items is altered. For instance: Initially, there are 100 items in the scroll. Upon running the "reloadItems()" function to change the 100 i ...

Exploring type definition for function arguments in TypeScript and React

There is a high-order component (HOC) designed to store the value of one state for all input and select elements. The output function accepts arguments ({text: Component, select: Component}). An error is displayed while typing an argument: TS2322: Type &ap ...

Encountered a higher number of hooks rendered compared to the previous render error on a component without any conditional hook usage

Within my codebase, I have a component that is responsible for rendering a clickable link to initiate a file upload process. import { gql, useLazyQuery, useMutation } from '@apollo/client'; import { useEffect, useState } from 'react'; i ...

Changing the baseHref for ng serve in the latest version of Angular 14

My angular.json file has a set "baseHref" to '/bui' for deploying static files. However, when using ng serve on port 4200 and navigating to https://localhost:4200, I receive the message: Cannot GET / This issue is caused by the baseHref configur ...

Using Typescript to specify the parameter type of a function as a generic function

After creating a function called compose, it looks like this: const composeTyped = <T, U, R>(f: (x: T) => U, g: (y: U) => R) => (x: T) => g(f(x)); It appears to me that both functions f and g fall under the type fGeneric, which is define ...

Can you explain the significance of using an exclamation mark after defining a variable in TypeScript?

As I delve into TypeScript in an effort to enhance my programming skills, I have encountered the use of exclamation marks when defining variables. An example of this can be seen in the following code snippet: protected _db!: CheckpointDB ...

An infinite number of data requests are initiated asynchronously within a loop

When using Angular with TypeScript, I have the following component class: @Injectable() @Component({ selector: 'app-mycomponent', templateUrl: './mycomponent.component.html' }) export class MyComponent implements OnInit{ p ...

Encountering issues with managing CometD channels within Angular 2

After dabbling in Angular2 and Typescript, I decided to challenge myself by creating an application using plain javascript with the CometD library. The goal of this app was to retrieve data from a CometD channel and present it to the user in some way. So, ...

The Mat-paginator is refusing to align to the right edge when scrolling the table horizontally in an Angular application

Overview: My Angular component features a table with Angular Material's mat-table and paginator. Despite fetching data from a source, the paginator fails to float right when I scroll horizontally. Sample Code: <!-- Insert your code snippet below ...

Expanding index signature in an interface

Is there a way to redefine the old index signature when trying to extend an interface with different property types? I am encountering an error when adding new properties that have a different type from the original index signature. interface A { a: num ...

Creating data types from the name of the route in vue-router route[x]

I am attempting to generate route names based on the routes defined in the Vue Router. My goal is to utilize a helper function called findRouteByName() to locate a specific route. However, I encountered an issue when trying to define the parameters of the ...

Unexpected error encountered in Angular 2 beta: IE 10 displays 'Potentially unhandled rejection [3] SyntaxError: Expected'

Question regarding Angular 2 Beta: I am starting off with a general overview in the hopes that this issue is already recognized, and I simply overlooked something during my research. Initially, when Angular 2 Beta.0 was released, I managed to run a basic m ...

Issues arise with Typescript compiler on Windows systems due to soft symlinks causing compilation failures

In my TypeScript project, symlinks function properly on both macOS and Linux. However, when executing tsc in git-bash on Windows (not within WSL), the files cannot be resolved by tsc. ...