In Angular 8, a communication service facilitates interaction between parents and children

Using a Sharing service, I am able to pass data from my app component to the router-outlet render component. While I have been successful in passing strings and other data, I am now looking for a way to retrieve data from an API and share it with a component.

In the app component, there is a checkbox that allows users to select a category of books. When a new item is checked, the ChangeMessage method is called to send the Categoryid ID. This method then updates the list of books and shares it with another component for display:

@Injectable({providedIn:'root'})
export class DataService {
  private Messagesource = new Subject<any>();
  curentMessage$ = this.Messagesource.asObservable()
  constructor(private http: HttpClient, @Inject('BASE_URL') public url: string) { }
  ChangeMessage(message: any) {
    let result = this.http.get<Book[]>(this.url + 'api/Books');
    this.Messagesource.next(result);
  }
}

In the other component, the list of books is retrieved and updated as follows:

export class BookComponent implements OnInit {

  booklist: Book[]
  constructor(public service:CategoryServic,private ds:DataService) {}

    ngOnInit(): void {
      this.ds.curentMessage$.subscribe(x => this.booklist = x)
  }  
}

Answer №1

Identify the issue with the code snippet below

let output = this.http.get<Book[]>(this.url + 'api/Books');

It should be noted that the above code will result in an Observable, but your requirement is to pass a variable of type Book[], not an observable, to the next method's argument. Additionally, when using HttpClient, the get call will not execute unless you subscribe to the result. To gain a better understanding, let's refer to what Angular documentation states about HttpClient methods (check here):

An HttpClient method does not initiate the HTTP request until you invoke subscribe() on the observable returned by that method. This applies to all HttpClient methods.

In addition to that, I usually initialize the constructor of the Subject with a default value, which can help you grasp the concept better. For instance, if I have to track whether a user is logged in or not, I would initialize my subject as:

private isLoggedIn: BehaviorSubject<boolean> = new BehaviorSubject(false); 

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

An error occurred in the ngrx store with Angular during production build: TypeError - Unable to access property 'release' of undefined

After deploying my application and running it, I encountered an issue that seems to be happening only during production build at runtime. At this point, I am uncertain whether this is a bug or if there is a mistake in my code. The error "TypeError: Cannot ...

Tips for addressing the browser global object in TypeScript when it is located within a separate namespace with the identical name

Currently diving into TypeScript and trying to figure out how to reference the global Math namespace within another namespace named Math. Here's a snippet of what I'm working with: namespace THREE { namespace Math { export function p ...

Issues related to the Angular Http module

When attempting to launch my app, I encountered the following error: ERROR Error: StaticInjectorError(AppModule)[ApiUserService -> HttpClient]: StaticInjectorError(Platform: core)[ApiUserService -> HttpClient]: NullInjectorError: No provide ...

Getting started with accessing an API using Angular 2

I am seeking a way to navigate outside of my Angular 2 application to mywebsite.com/api. This link should direct me to an API application hosted on the same server. Here is my current route configuration. export const routes: Routes = [ {path: '& ...

Divs are not being organized into rows correctly due to issues with Bootstrap styling

I have implemented Bootstrap in my Angular application. The stylesheet link is included in my Index.html file as follows: <link rel="stylesheet" href="../node_modules/bootstrap/dist/css/bootstrap.css"> In addition to that, I have listed Bootstrap a ...

Creating an interceptor to customize default repository methods in loopback4

Whenever I attempt to access the default repository code, I need to manipulate certain values before triggering the default crud function in the repository. How can I accomplish this? For example: ... @repository.getter('PersonRepository') priva ...

The .value property on the form group displays numeric values as either null or an empty string

I'm encountering an issue with extracting data from a form group. Within my code, there is a formGroup named lineitemForm, and I am attempting to structure this form group as follows: private formatTransferData() { const depositDates = this.get ...

What exactly does the $any() type cast in Angular do and how is it used?

While browsing the Angular.io site, I came across this title: The $any() type cast function There are instances where a binding expression may trigger a type error during AOT compilation and it is not possible or difficult to fully specify the type. To re ...

Exploring Mixed Type Arrays Initialization in Typescript using Class-Transformer Library

In my class, I have a property member that is of type array. Each item in the array can be of various types such as MetaViewDatalinked or MetaViewContainer, as shown below class MetaViewContainer{ children: (MetaViewDatalinked | MetaViewContainer)[]; ...

A guide to extracting attribute values from HTML using Angular 4

I am currently working on an Angular 4 project where I needed to implement drag and drop functionality. To achieve this, I utilized the ng2-dragula plugin. Now, I have a new requirement which involves extracting the data-id attribute from each row after it ...

Having trouble retrieving values from radio buttons in Angular 2 forms

Having trouble displaying the values of radio button inputs in Angular 2 forms. ...

Ways to update the color of the mat-dialog-title using the material theme

Currently, I am utilizing the Angular Material Dialog and have been attempting to dynamically change the title color of the dialog based on the material theme. <h1 mat-dialog-title color="primary">{{ title }}</h1> Even though setting ...

Developing an angular progress bar

I've been working on creating a progress bar in Angular using the mmat-stepper. Here's a snippet of my code: import { BrowserModule } from '@angular/platform-browser'; import { NgModule } from '@angular/core'; import { AppCom ...

Definition of a Typescript Global.d.ts module for a function that is nested within another function

Simply put, I have a npm module that exports a function along with another function attached to it: // @mycompany/module ... const someTool = (options) => { // do some cool stuff }; someTool.canUseFeature1 = () => { return canUseSomeFeature1(); ...

The reason for the Jest failure is that it was unable to locate the text of the button

As someone who is new to writing tests, I am attempting to verify that the menu opens up when clicked. The options within the menu consist of buttons labeled "Edit" and "Delete". However, the test fails with the message: "Unable to find an element with te ...

Experience feelings of bewilderment when encountering TypeScript and Angular as you navigate through the

Exploring Angular and TypeScript for an Ionic project, I am working on a simple functionality. A button click changes the text displayed, followed by another change after a short delay. I'm facing confusion around why "this.text" does not work as exp ...

Attempting to publish and install a unique angular2 component using NPM and Angular-CLI results in successful compilation only on the initial try

I am facing a peculiar and frustrating issue. The problem revolves around an Ng2 component I have developed called via-date-picker. My goal is to publish it on NPM so that it can be easily utilized in other projects. To achieve this, I converted it into a ...

Can you explain the functionality of this Angular CLI instruction?

Can you explain the function of this command in the Angular command line? npx ng g s weather --flat false Referenced in: Angular 6 for Enterprise Ready Web Applications, page 61 ...

Steps to apply a decorator to a function that is not a nestjs route

NestJS Hello there! I am currently facing an issue where I need to apply a decorator to a function that is not serving as an endpoint or route. To illustrate, here is what I have in mind: class Controller { @Get('/') firstMethod() { ...

The mat-menu generated with ngFor fails to activate the click function

I'm encountering difficulties when implementing a mat-menu using *ngfor I have consulted this response How can I utilize *ngFor with mat-menu and mat-menu-item? and although I believe I am following the same approach, I am still experiencing errors. ...